美文网首页
正则-replace实战

正则-replace实战

作者: 子心_ | 来源:发表于2019-06-16 09:43 被阅读0次
    var str = "20151213";
    var ary = ["零","壹","贰","叁","肆","伍","陆", "柒","捌","玖"];
    str = str.replace(/\d/g, function () {
      var num = arguments[0];
      var str = ary[num];
      return str;
    });
    console.log(str);
    

    replace的分组替换实例:

    var str = "my name is {0}, my age is {1}, i come from {2}, i love {3}~";
    var ary = ["易文", 25, "湖南", "javaScript"];
    var reg = /{(\d+)}/g;
    str = str.replace(reg, function (larCon, smallCon, index, input) {
      // larCon --> arguments[0] 每一次执行replace大正则捕获的内容
    // smallCon --> arguments[1] 每一次执行replace小正则捕获的内容
        return arg[arguments[1]];
    });
    console.log(str)
    

    相关文章

      网友评论

          本文标题:正则-replace实战

          本文链接:https://www.haomeiwen.com/subject/qajifctx.html