JavaScript string is replaced. How to check if there was a match?

Is there any other way to find out if there was a match in the String.replace method and then search for the result in it? Or is there another method that gives me this information? I need a behavior similar to PHP preg_replace, where I can add an optional argument that will be filled with the number of replacements made.

+3
source share
1 answer

You can do this with a regex and function:

var count=0;
    text.replace(replaceRegexp,function(){
        count++;
        return replacement;
    });

Thus, the variable "count" 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
+2
source

Source: https://habr.com/ru/post/1758350/


All Articles