Javascript string.replace 方法中 函数参数的使用


豁然发现 replace方法真心是个好东西


replace的语法是:

stringObject.replace(regexp/substr,replacement)

第一个参数是一个字符串或者正则表达式

第二个参数是要替换的字符 也可以是函数

对于正则表达式配合$开头的待替换字符的各种奇技淫巧 网上很多地方都有 我也便懒得研究了

主要是当第二个参数是函数的时候 应该怎么用呢?


如下代码既是试验代码也是应用代码

它用了两种方法将一个字符串格式化

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <div class="datatest" data-pre="pre"></div>
    <script>
    replacement=["Javascript","String"]


    str1="here is a $s test of $s replace";
    var i = -1;
    str1 = str1.replace(/\$s/g,function(a,b,c,d){
        i++;
        console.log(a + " " + b + " " + c + " " + d + " " + i);
        return replacement[i];
    });
    console.log(str1);




    str2="here is a $0 test of $1 replace";
    str2 = str2.replace(/\$(\d+)/g,function(a,b,c,d){
        console.log(a + " " + b + " " + c + " " + d);
        return replacement[b];
    });
    console.log(str2);
    </script>
</body>
</html>


在chrome下输出为:

$s 10 here is a $s test of $s replace undefined 0
$s 21 here is a $s test of $s replace undefined 1
here is a Javascript test of String replace
$0 0 10 here is a $0 test of $1 replace
$1 1 21 here is a $0 test of $1 replace
here is a Javascript test of String replace


显然的,对于没有变量的正则 replacement 函数有3个参数: 匹配到的字符串 匹配到的字符串在原字符串中的位置 原字符串

对于有变量的正则replacement 函数有4个参数: 匹配到的字符串 变量值 匹配到的字符串在原字符串中的位置 原字符串


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值