且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何知道 JavaScript string.replace() 是否做了什么?

更新时间:2023-11-21 18:07:10

一个简单的选择是在替换之前检查匹配:

A simple option is to check for matches before you replace:

var regex = /i/g;
var newStr = str;

var replaced = str.search(regex) >= 0;
if(replaced){
    newStr = newStr.replace(regex, '!');
}

如果你也不想这样,你可以滥用 replace 回调来一次性实现:

If you don't want that either, you can abuse the replace callback to achieve that in a single pass:

var replaced = false;
var newStr = str.replace(/i/g, function(token){replaced = true; return '!';});