Alex Kapranoff Alex Kapranoff - 1 year ago 64
Javascript Question

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


function returns the new string with the replaces, but if there weren't any words to replace, then the original string is returned. Is there a way to know whether it actually replaced anything apart from comparing the result with the original string?

Answer Source

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

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

var replaced = >= 0;
    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 '!';});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download