简体   繁体   English

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

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

I got inputs with names like this: 我输入的名称如下:

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

What I want to do is to replace the character in the first clamp (day[ 0 ][0], event[ 0 ][0][0][0]) ... But the characters in the clamps may change ... 我想做的是替换第一个钳位中的字符(day [ 0 ] [0],事件[ 0 ] [0] [0] [0])...但是钳位中的字符可能会更改.. 。

Here is a first code draft 这是第一个代码草案

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 );

} );

The .attr() method accepts a function, so you don't need to manually iterate over each element, retrieve the name attribute and update it. .attr()方法接受一个函数,因此您无需手动遍历每个元素,检索name属性并对其进行更新。

You can just pass a function and return the replaced attribute: 您可以只传递一个函数并返回替换的属性:

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

The expression /^(\\w+)\\[.*?\\]/ will select the first set of brackets after one or more \\w characters (which are then captured and then replaced). 表达式/^(\\w+)\\[.*?\\]/将选择一个或多个\\w字符(然后被捕获然后替换)之后的第一组括号。

Which would return: 哪个会返回:

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

As a side note, \\w+ will match one or more of the following characters: [a-zA-Z0-9_] . 附带说明, \\w+将匹配以下一个或多个字符: [a-zA-Z0-9_] If the characters differ, you may want to use: 如果字符不同,则可能要使用:

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

Alternatively, if you want to update the value in the first set of brackets based on the index, you could use: 或者,如果要基于索引更新第一组括号中的值,则可以使用:

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

Which would return: 哪个会返回:

<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]">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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