说说 String.prototype.replace()

实际开发中我们常常使用str.replace()来做替换。但似乎很少用到它的模式匹配功能。

说说 String.prototype.replace()


看看下面妙用模式匹配的例子

var re = /(w+)s(w+)/;
var str = “John Smith”;

var newstr = str.replace(re, “$2, $1”);

// Smith, John

console.log(newstr);

const caller = function(n) {

  return n.replace(/(d)(?=(d{3})+$)/g, “$&,”)

}

const b = caller( 123234238329 )

// 123,234,238,329

console.log(b)

注意正则表达式?=的匹配方式。完全匹配时之匹配”d”部分

参考链接:

String.prototype.replace() – JavaScript | MDN

w3c

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容