Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment a number on each replace in javascript

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

like image 772
EMM Avatar asked May 13 '15 16:05

EMM


People also ask

How to increment a value in JavaScript?

The increment operator ( ++ ) increments (adds one to) its operand and returns the value before or after the increment, depending on where the operator is placed.

What is++ I in JavaScript?

The Prefix Operator ++i is called a prefix operator. This means that the value of the variable is incremented before it is used in the expression. For example, consider the following code: let i = 0;console.log(++i); // Prints 1console.log(i); // Prints 1.

What is replace () in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

Can you increment a string in JavaScript?

Use the String. fromCharCode() method to increment a letter in JavaScript, e.g. String. fromCharCode(char. charCodeAt(0) + 1) .


2 Answers

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;
});
like image 142
user1106925 Avatar answered Oct 15 '22 03:10

user1106925


Try:

var string = "This is this";
var number = 0;
string.replace(/is/g, function() {
  number++;
  return "as";
});
alert(number);
like image 31
jcubic Avatar answered Oct 15 '22 04:10

jcubic