Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 958
Yahoo Avatar asked May 17 '26 23:05

Yahoo


1 Answers

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
like image 197
mck89 Avatar answered May 19 '26 13:05

mck89



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!