Use RegExp to match a parenthetical number then increment it

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) + ")";
});

Leave a Comment