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...! :-)

EMM
  • 171
  • 2
  • 12
  • 1
    You mean you want to count the replacements ? – Denys Séguret May 13 '15 at 16:37
  • 1
    You can use a [function as a second parameter](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) to do that. – ForguesR May 13 '15 at 16:39
  • `string.replace("is", "as");` will only replace the first occurrence though. Are you planning to call `replace` multiple times? – Felix Kling May 13 '15 at 16:41
  • @FelixKling No I don't want to call the replace multiple times. – EMM May 13 '15 at 17:32
  • @ForguesR But second parameter uses to replace the text, and I also want to replace the text as well – EMM May 13 '15 at 17:34

2 Answers2

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;
});
  • But I also want to replace the text – EMM May 13 '15 at 17:32
  • 1
    @EMM: just return the replacement. – Felix Kling May 13 '15 at 17:34
  • @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); – EMM May 13 '15 at 17:40
  • @FelixKling See My Answer below – EMM May 13 '15 at 17:43
  • @EMM: matches are passed as arguments to the function. Please read the MDN documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – Felix Kling May 13 '15 at 17:44
  • @EMM: You're not describing clearly what you want. What is `$1` supposed to be? If you want it to be the value of `number` then use string concatenation like normal. `return "as" + number + "as";` –  May 13 '15 at 18:13
10

Try:

var string = "This is this";
var number = 0;
string.replace(/is/g, function() {
  number++;
  return "as";
});
alert(number);
jcubic
  • 61,973
  • 54
  • 229
  • 402