How to know if JavaScript string.replace() did anything?

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, '!');
}

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 '!';});

As a workaround you can implement your own callback function that will set a flag and do the replacement. The replacement argument of replace can accept functions.


Comparing the before and after strings is the easiest way to check if it did anything, there's no intrinsic support in String.replace().

[contrived example of how '==' might fail deleted because it was wrong]