6

In javascript, I have a string which contains numbers, and I want to increment 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 regex, is it possible to perform operations (addition in this case) on the matched backreference?

A found a similar question using Ruby:

string.gsub(/(\d+)/) { "#{$1.to_i + 1}"}

2 Answers 2

7

Use string.replace with a 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 matching groups then the first argument to the function will be the entire match and each following argument will be the 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."
Sign up to request clarification or add additional context in comments.

1 Comment

fast. I ended up using arguments[n] (versus x) in my actual code (because I had multiple backreferences)
1

Found it.

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)

Should have guessed an anonymous function would work.

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.