How to perform operations on backreference links in regex in javascript?

In javascript, I have a string that contains numbers, and I want to increase the values ​​by one.

Example:

var string = "This is a string with numbers 1 2 3 4 5 6 7 8 9 10";

var desiredResult = "This is a string with numbers 2 3 4 5 6 7 8 9 10 11";

Using a regular expression, is it possible to perform operations (adding in this case) in accordance with reverse regression?

A found a similar question using Ruby:

string.gsub(/(\d+)/) { "#{$1.to_i + 1}"}
+5
source share
2 answers

Use string.replacewith function as the second argument:

var s1 = "This is a string with numbers 1 2 3 4 5 6 7 8 9 10";
var s2 = s1.replace(/\d+/g, function(x) { return Number(x)+1; });
s2; // => "This is a string with numbers 2 3 4 5 6 7 8 9 10 11"

Note that if you use comparable groups, the first argument to the function will be a complete match, and each subsequent argument will be a numbered matching group.

var x = "This is x1, x2, x3.";
var y = x.replace(/x(\d+)/g, function(m, g1) {
  return "y" + (Number(g1)+1);
});
y; // => "This is y2, y3, y4."
+7
source

Found.

var string = "This is a string with Numbers 1 2 3 4 5 6 7 8 9 10";
var desiredResult = "This is a string with Numbers 2 3 4 5 6 7 8 9 10 11";
var actualResult = string.replace(/([0-9]+)/g, function() {
    return parseInt(arguments[1])+1 
});
console.log(actualResult)

An anonymous function should have been guessed.

+1

All Articles