3

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
  • Can you give an example? Commented Aug 6, 2010 at 9:08

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.