简体   繁体   中英

Replace character in a string using RegEx JS

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM