Increment a number in a string in with regex

Solution 1:

How about:

'url1'.replace(/\d+$/, function(n){ return ++n }); // "url2"
'url54'.replace(/\d+$/, function(n){ return ++n }); // "url55"

There we search for a number at the end of the string, cast it to Number, increment it by 1, and place it back in the string. I think that's the same algo you worded in your question even.

Reference:

  • String.prototype.replace - can take a regex

Solution 2:

Simple. Use a substitution function with regular expressions:

s = 'abc99abc';
s = s.replace(/\d+/, function(val) { return parseInt(val)+1; });

will set variable s to: abc100abc

But it gets more complicated if you want to make sure you only change a certain parameter in the URL:

s = '?foo=10&bar=99';
s = s.replace(/[&?]bar=\d+/, function(attr) {
  return attr.replace(/\d+/, function(val) { return parseInt(val)+1; });
});

will set variable s to: ?foo=10&bar=100

Solution 3:

Looks OK. You might want to use a regex like ^(.*?)(\d+)$, making sure the number you're grabbing is at the end of the string.

Solution 4:

You can use replace and pass it a function to use to replace the matched section:

str.replace(/\d+/, function(number) { return parseInt(number, 10) + 1; });