Skip to content Skip to sidebar Skip to footer

How Can I Increment A Number Matched Via Regex?

I am adding a new field in one of my web apps, for visitors to add a product. Pushing 'add a product' clones one of the existing inputs, and I set it to a blank value. I need to u

Solution 1:

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

So,

*edit:

this should work

"product[0][0][3][title]".replace(/(^product\[\d+\]\[\d+\]\[)(\d+)(\]\[.+\])/, function(fullMatch, n, a, o) {
    return n + (Number(a) + 1) + o;
});

Solution 2:

A more iterative approach:

r = /^(product\[\d+\]\[\d+\]\[)(\d+)(\]\[[a-z]+\])$/;
m = s.match(r);
if (!m) { /* do something smart; */ }
s.replace(r, "$1" + (Number(m[2]) + 1) + "$3");

I added a capture group at the head and tail of your regex. Then match, increment, and reassemble the string.

+1 for the match function on the regex though, I didn't know that trick.

Solution 3:

Based on Andrew's answer, but corrected to return entire string:

"product[0][0][3][title]".replace (
    /^(product\[\d+\]\[\d+\]\[)(\d+)(\]\[.+\])/,
    function(fullMatch, pre, n, post) {
        return pre + (Number(n) + 1) + post;
    }
);

Post a Comment for "How Can I Increment A Number Matched Via Regex?"