Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 511
Alex Kapranoff Avatar asked Mar 10 '11 08:03

Alex Kapranoff


People also ask

Does string replace replace all occurrences?

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.

Does replace works on string?

The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.

How does replace method work in JavaScript?

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.

Does string replace 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.


2 Answers

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 '!';}); 
like image 84
Kobi Avatar answered Oct 10 '22 02:10

Kobi


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]

like image 34
Alnitak Avatar answered Oct 10 '22 01:10

Alnitak