JavaScript - 替换 name 属性中第一个方括号之间的值

JavaScript - Replace the value between the first square brackets in a name attribute

本文关键字:方括号 之间 第一个 替换 name 属性 JavaScript      更新时间:2023-09-26

>我得到了这样名称的输入:

<input class="serialize" name="day[0][0]" />
<input class="serialize" name="event[0][0][0][0]" />

我想做的是替换第一个夹子(day[0][0],事件[0][0][0][0])中的字符......但是夹子中的字符可能会改变...

这是最初的代码草案

jQuery( this ).find( '.serialize' ).each( function( index ) {
    var attr = jQuery( this ).attr( 'name' );
    attr = attr.replace( 'regex magic' ); // This line is the problem
    jQuery( this ).attr( 'name', attr );
} );

.attr() 方法接受一个函数,因此您无需手动迭代每个元素、检索 name 属性并更新它。

你可以只传递一个函数并返回替换的属性:

$('.serialize').attr('name', function () {
  return this.name.replace(/^('w+)'[.*?']/, '$1[20]');
});

表达式/^('w+)'[.*?']/将选择一个或多个'w字符后的第一组括号(然后捕获这些字符,然后替换这些字符)。

这将返回:

<input class="serialize" name="day[20][0]">
<input class="serialize" name="event[20][0][0][0]">

作为旁注,'w+将匹配以下一个或多个字符:[a-zA-Z0-9_] .如果字符不同,您可能需要使用:

$('.serialize').attr('name', function () {
  return this.name.replace(/^(.*?)'[.*?']/, '$1[20]');
});

或者,如果要根据索引更新第一组括号中的值,可以使用:

$('.serialize').attr('name', function (i) {
  return this.name.replace(/^('w+)'[.*?']/, '$1[' + i + ']');
});

这将返回:

<input class="serialize" name="day[0][0]">
<input class="serialize" name="event[1][0][0][0]">
<input class="serialize" name="somethingelse[2][0][0][0]">