The replace
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?
The String type provides you with the replace() and replaceAll() methods that allow you to replace all occurrences of a substring in a string and return the new version of the string.
The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
The JavaScript String replace() method returns a new string with a substring ( substr ) replaced by a new one ( newSubstr ). Note that the replace() method doesn't change the original string. It returns a new string.
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 '!';});
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With