Ryan Hipkiss
Ryan Hipkiss

Reputation: 678

Increment 3rd occurence of digit in string with javascript

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.

Upvotes: 1

Views: 77

Answers (3)

Valdi_Bo
Valdi_Bo

Reputation: 30971

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.

Upvotes: 0

Jamiec
Jamiec

Reputation: 136074

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);

Upvotes: 2

anubhava
anubhava

Reputation: 784898

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]"

Upvotes: 1

Related Questions