1

I have a number of inputs names with last digit changing:

<input name="ProductsLang[1][text][0]">
<input name="ProductsLang[1][text][1]">
<input name="ProductsLang[1][text][2]">

I'm adding new inputs dynamically and I need to recalculate all indexes accordingly due to I might add one in between. So I have a small function with regex to replace them:

$('input').each(function(i) {
    var matches = $(this).attr('name').match(/ProductsLang\[\d+\]\[[^\]]+\]\[(\d+)\]/);
    var newName = $(this).attr('name').replace(matches[1], i);
    $(this).attr('name', newName);
});

and it works weird... instead of changing last digit I can get a result like this:

<input name="ProductsLang[1][text][0]">
<input name="ProductsLang[1][text][1]">
<input name="ProductsLang[2][text][1]">
<input name="ProductsLang[1][text][3]">

Why does replace works like that? Help me figure it out. All I need is to increment last digit.

2
  • 1
    Try just $(this).attr('name', $(this).attr('name').replace(/\[\d+]$/, '[' + i + ']')); instead of the 3 lines inside each. Commented Oct 9, 2017 at 21:18
  • 1
    Thanks, its works. Commented Oct 10, 2017 at 6:32

1 Answer 1

1

Replace the body of your .each with this line

$(this).attr('name', $(this).attr('name').replace(/\[\d+]$/, '[' + i + ']'));

The /\[\d+]$/ pattern matches a [, 1 or more digits and then a ] at the end of the string (due to the $ anchor).

See the regex demo online.

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

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.