String.replace与String.format

  字符串的替换函数replace平常使用的频率非常高,format函数通常用来填补占位符。下面简单总结一下这两个函数的用法。

一、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的字符串。

  拿上面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:        乐小天    ;
乐小天
*/

二、String.format的实现

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

  1.format实现:

//扩展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是这么定义的:

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

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

  

  

 

转载于:https://www.cnblogs.com/longhx/p/5478601.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值