Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  94] [ 2]  / answers: 1 / hits: 18907  / 14 Years ago, thu, march 10, 2011, 12:00:00

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?


More From » regex

 Answers
7

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

[#93347] Tuesday, March 8, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grayson

Total Points: 36
Total Questions: 113
Total Answers: 95

Location: Tonga
Member since Fri, Aug 21, 2020
4 Years ago
grayson questions
;