1

I have the following string:

[group][100][250][3][person]

and I need to increment the number 3. I tried the regex /\[\d+\]/ which matches all 3, but I couldn't get anywhere from here.

5
  • is the string always formatted in this way - AKA do you know in advance the position of the 3? Commented Jun 2, 2017 at 10:13
  • Yes. It will always be in that format, although the numbers 100 and 250 could be 123456 and 654321 for example. They could be any length. Commented Jun 2, 2017 at 10:14
  • Your question is unclear since you don't explain why you want [3] and not [100] or [250]. Reading your previous question I suspect that you choose this one for its position, however you don't say if you want the last or the third. Commented Jun 2, 2017 at 10:23
  • Possible Duplicate of Replace nth occurrence of string Commented Jun 2, 2017 at 10:25
  • @CasimiretHippolyte Title clearly says "3rd" Commented Jun 2, 2017 at 10:25

3 Answers 3

2

You could do it by matching all 3 of your numeric values and just increment the third:

var regex = /\[(\d+)\]\[(\d+)\]\[(\d+)\]/g

var input = "[group][100][250][3][person]";

var result = input.replace(regex, function(match,p1,p2,p3){
  return "[" + p1 + "][" + p2 + "][" + (parseInt(p3,10) + 1) + "]"
})
console.log(result);

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

Comments

1

You can use .replace with a callback function:

var s = "[group][100][250][3][person]";
var repl = s.replace(/((?:\[\d+\]){2}\[)(\d+)\]/,
          function($0, $1, $2) { return $1 + (parseInt($2)+1) + ']'; }
);

console.log(repl);
//=> "[group][100][250][4][person]"

Comments

0

To capture "your" string, try the below regex:

(?:\[\d+\]){2}\[(\d+)\]

How it works:

  • (?:...){2} - a non-capturing group, occuring 2 times.
  • \[\d+\] - containing [, a sequence of digits and ].
  • [, a capturing group - sequence of digits and ].

The text you want to capture is in the first capturing proup.

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.