String.replace与String.format

  字符串的替换函数replace日常使用的频率很是高,format函数一般用来填补占位符。下面简单总结一下这两个函数的用法。前端

1、String.replace的两种用法

  replace的用法如:replace(regexp, string|fn);第一个参数都是正则表达式,第二个参数能够是要替换的字符串,也能够是带返回值的函数,它的功能就是拿第二个参数替换匹配的值。正则表达式

  1.replace(regexp, string):我想把“乐小天”中的“小”替换成“大”,以下所示。框架

console.log("乐小天".replace(/小/g, "大"));//乐大天

//trim的实现方式 console.log(" 乐小天 ".replace(/(^\s+)|(\s+$)/g, ""));//乐小天

  2.replace(regexp, fn);fn这个回调函数能够有四种参数,第一种参数是匹配regexp的字符串;第二种为匹配regexp子表达式的字符串(有几个自表达式,顺延对应几个参数,若是没有子表达式,则第二个参数为第三种参数);第三种参数为regexp匹配字符串在字符串中的索引;第四种参数为当前调用replace的字符串。less

  拿上面trim的实现为例,它的正则表达式包含两个子表达式:(^\s+)和(\s+$);因此回调函数应该有5个参数。固然,若是没有子表达式,则只有三种参数。函数

console.log("        乐小天    ".replace(/(^\s+)|(\s+$)/g, 
    function(match, matchChild1, matChild2, index, strObj){
        console.log("match:" + match + ";");
        console.log("matchChild1:" + matchChild1 + ";");
        console.log("matChild2:" + matChild2 + ";");
        console.log("index:" + index + ";");
        console.log("strObj:" + strObj + ";");
        return "";
    }
));
/**
match:        ;
matchChild1:        ;
matChild2:undefined;
index:0;
strObj:        乐小天    ;
match:    ;
matchChild1:undefined;
matChild2:    ;
index:11;
strObj:        乐小天    ;
乐小天
*/

2、String.format的实现

  有的时候咱们事先不知道字符串对应位置应该替换成什么,因此咱们用占位符“{数字}”在字符串中进行预先占位,在真正肯定的时候才将其替换掉。说白了就是将未知的替换字符封装成参数,让替换逻辑这个不变的部分与替换参数这个变化部分进行分离。this

  1.format实现:spa

//扩展format
String.prototype.format = String.prototype.format || function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) {
        return typeof args[number] != 'undefined' ? args[number] : match;
    });
};

console.log("{0}是个{1}帅哥!".format('孙悟空', '大'));//孙悟空是个大帅哥!

  2.format替换字符在form校验中用到的比较多,好比前端UI框架MiniUI的校验对象VType是这么定义的:prototype

mini.VTypes = {
   minDateErrorText : "Date can not be less than {0}",
   maxDateErrorText : "Date can not be greater than {0}",
   ...  
};

  在返回错误信息的时候将对应的边界值替换掉“{0}”code

相关文章
相关标签/搜索