9

I want to increment a number each time string.replace() replace a sub-string. for example in:

var string = "This is this";
var number = 0;
string.replace("is", "as");

When string.replace first is of This number becomes 1, then for second is of is number becomes 2 and finally for last is of this number becomes 3. Thanks in advance...! :-)

5
  • 1
    You mean you want to count the replacements ? Commented May 13, 2015 at 16:37
  • 1
    You can use a function as a second parameter to do that. Commented May 13, 2015 at 16:39
  • string.replace("is", "as"); will only replace the first occurrence though. Are you planning to call replace multiple times? Commented May 13, 2015 at 16:41
  • @FelixKling No I don't want to call the replace multiple times. Commented May 13, 2015 at 17:32
  • @ForguesR But second parameter uses to replace the text, and I also want to replace the text as well Commented May 13, 2015 at 17:34

2 Answers 2

20

You can pass a function to .replace() and return the value. You also need to use a global regex to replace all instances.

var string = "This is this";
var number = 0;

document.body.textContent = string.replace(/is/g, function() {
    return ++number;
});

Sign up to request clarification or add additional context in comments.

6 Comments

But I also want to replace the text
@EMM: just return the replacement.
@FelixKling And what about this: var string = "This is this"; var number = 0; string.replace(/is/g, function() { number++; return "as $1 as"; }); alert(number);
@FelixKling See My Answer below
@EMM: matches are passed as arguments to the function. Please read the MDN documentation: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
|
10

Try:

var string = "This is this";
var number = 0;
string.replace(/is/g, function() {
  number++;
  return "as";
});
alert(number);

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.