2

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 the name Units needs to be literally matched first.

I am trying something like this:

test.replace(/(?:Units\[|\_+)(\d+)/g, function(m, i) { return parseInt(m) + 1 })

My problem is that without positive lookbehind I cannot seem to match only the digits. I am trying to build the regex in such a way that only the digits form part of the capture group, and I can therefore replace them.

It's easy to do in c#, but the javascript match function works a little differently.

Despite the non capture specification of (?: the Units[ seems to form part of the match. Since javascript does not support look behind, I am at a loss as to how to complete this.

4
  • The first argument to the callback function is the entire match. The first group in the regex is the second argument. Commented Mar 21, 2016 at 15:10
  • (?: just means it's not in a capturing group, it's still in the overall substring that's parsed, and then your digits are in the first captured group. Commented Mar 21, 2016 at 15:10
  • Hello XY Problem - it's been a few weeks. Commented Mar 21, 2016 at 15:11
  • Specifying a function as a parameter to String.prototype.replace() this may be of help to you. Commented Mar 21, 2016 at 15:15

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

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.