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...! :-)
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.
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.
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.
Use the String. fromCharCode() method to increment a letter in JavaScript, e.g. String. fromCharCode(char. charCodeAt(0) + 1) .
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;
});
Try:
var string = "This is this";
var number = 0;
string.replace(/is/g, function() {
number++;
return "as";
});
alert(number);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With