需要正则表达式和javascript的帮助

Need help with regular expression and javascript

本文关键字:帮助 javascript 正则表达式      更新时间:2023-09-26

我有以下问题:我使用克隆脚本克隆用于cms选项的输入字段。根据字段名,在数据库中创建选项数组。

我现在有以下字段:

options[categories][1][3]

,并希望通过使用计数器变量增加第一个数字,如:

options[categories][2][3]
options[categories][3][3]

然而,我不熟悉正则表达式,所以我希望有人能提供一个str.replace代码,帮助我用我的计数器变量替换第一个数字。

提前感谢!

……代码:…

现在看起来是这样的:

if ( $(clone).attr('name') ){
                newid = $(clone).attr('name');
                var position = newid.lastIndexOf("[");
                newid = newid.substring(0, position)+ '[' + (counter +1) + ']';
                $(clone).attr('name', newid);
            };      
Html字段:

<input type="checkbox" value="1" name="options[categories][1][3]">

3是类别id, 1是我需要该类别的选项。克隆脚本将生成:

<input type="checkbox" value="1" name="options[categories][1][4]"> 

现在-但我需要:

<input type="checkbox" value="1" name="options[categories][2][3]">

我认为这是一个正则表达式问题,因为最简单的解决方案是搜索[categories][anyvalue]并将其替换为[categories][counter]

可以使用正则表达式替换括号中的第一个数字。这样的:

if ( $(clone).attr('name') ) {
    var newid = $(clone).attr('name');
    newid = newid.replace(/'[[0-9]*']/, '[' + (counter + 1) + ']');
    $(clone).attr('name', newid);
};