Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use RegExp to match a parenthetical number then increment it

I've been trying to find a way to match a number in a Javascript string that is surrounded by parenthesis at the end of the string, then increment it.

Say I have a string:

var name = "Item Name (4)";

I need a RegExp to match the (4) part, and then I need to increment the 4 then put it back into the string.

This is the regex I have so far:

\b([0-9]+)$\b

This regex does not work. Furthermore, I do not know how to extract the integer retrieved and put it back in the same location in the string.

Thanks.

like image 631
Joel Verhagen Avatar asked Jan 08 '09 03:01

Joel Verhagen


1 Answers

The replace method can take a function as its second argument. It gets the match (including submatches) and returns the replacement string. Others have already mentioned that the parentheses need to be escaped.

"Item Name (4)".replace(/\((\d+)\)/, function(fullMatch, n) {
    return "(" + (Number(n) + 1) + ")";
});
like image 146
Matthew Crumley Avatar answered Nov 05 '22 00:11

Matthew Crumley