简体   繁体   English

需要有关正则表达式和JavaScript的帮助

[英]Need help with regular expression and javascript

I've following problem: I use a clone script to clone input fields which are used for cms options. 我遇到了以下问题:我使用克隆脚本来克隆用于cms选项的输入字段。 Depending on the field name the option arrays are created in the db. 根据字段名称,在数据库中创建选项数组。

I have following field at the moment: 我目前有以下领域:

options[categories][1][3]

and want to increase the first number by using a counter variable like: 并希望通过使用计数器变量来增加第一个数字,例如:

options[categories][2][3]

options[categories][3][3]

... ...

However I'm not familiar with regular expressions so I hoped someone could provide a str.replace code which helps me to replace the first number with my counter variable. 但是我对正则表达式不熟悉,所以我希望有人可以提供一个str.replace代码,以帮助我用我的计数器变量替换第一个数字。

Thanks in advance! 提前致谢!

....... Code: ....... .......代码:.......

At the moment it looks like: 目前看起来像:

if ( $(clone).attr('name') ){
                newid = $(clone).attr('name');
                var position = newid.lastIndexOf("[");

                newid = newid.substring(0, position)+ '[' + (counter +1) + ']';
                $(clone).attr('name', newid);
            };      

Html field: HTML栏位:

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

3 is the category id, 1 is the option I need the category for. 3是类别ID,1是我需要其类别的选项。 The clone script would produce: 克隆脚本将产生:

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

at the moment - but I need: 目前-但我需要:

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

I think it's a regex problem because the easiest solution would be to search for [categories][anyvalue] and replace it with [categories][counter] 我认为这是一个正则表达式问题,因为最简单的解决方案是搜索[类别] [anyvalue]并将其替换为[类别] [计数器]

You could use a regular expression to replace the first number in brackets. 您可以使用正则表达式替换方括号中的第一个数字。 Like this: 像这样:

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

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

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