Skip to content Skip to sidebar Skip to footer

Replace And Increment Integer Value Using A Javascript Regex

Given the following string XXXX Units[4].Test XXXX I would like to replace each occurrence of Unit[x] with Unit[x+1]. I am trying to achieve this using a regular expression, as t

Solution 1:

You need to group the part before number and use that back-reference in replacement later:

test = test.replace(/(Units\[)(\d+)/ig, function($0, $1, $2) {
      return$1 + (parseInt($2)+1); })

//=> XXXX Units[5].Test XXXX

Note use of $1 and $2 in the callback function where $1 represents value Units[ and $2 is the number after it.

Post a Comment for "Replace And Increment Integer Value Using A Javascript Regex"