Is there any other way to find out if were was a match in String.replace method then searching in it's result? Or there is another method which give me that informations? I need behavior similar to PHP's preg_replace, where i can add optional argument which will be filled with the number of replacements done.
1 Answer
You can do it with a regexp and a function:
var count=0;
text.replace(replaceRegexp,function(){
count++;
return replacement;
});
In this way the "count" variable will contain the number of replacements. Example:
var text="test test",
replaceRegexp=/test/g,
replacement="foo";
var count=0;
text.replace(replaceRegexp,function(){
count++;
return replacement;
});
console.log(count); //2