简体   繁体   English

jQuery搜索替换字符串

[英]jQuery search replace string

I'm trying to rename some fields in a clone function, but I'm not sure how to rename (increase) the field name. 我正在尝试重命名克隆函数中的某些字段,但不确定如何重命名(增加)字段名称。

var tr = $copy.clone();
tr('input').each(function() {
  console.log(this.name); 
  this.name = something;
});

Example of field name: 字段名称示例:

field[subform][0][subsubform][2][name]

In this case I would need to increase [2] to [3] . 在这种情况下,我需要将[2]增加到[3] The name could have more or less brackets, but it's always the second last one that I would need to increase. 该名称可以有或多或少的括号,但它始终是我需要增加的倒数第二个括号。

How do I go about doing this? 我该怎么做呢?

Assuming it will always precede a [...] at the end of the string: 假设它总是在字符串末尾的[...]之前:

name.replace(/\[(\d+)\](\[[^\[]+\])$/, function (pattern, value, tail) {
    return "[" + (parseInt(value, 10) + 1) + "]" + tail;
});​

You can do it like this if it is always the second last one 如果它始终是倒数第二个,您可以这样做

var name = 'field[subform][0][subsubform][2][name]';
var firstStr = name.split('][').slice(0,-2);
var secStr = name.split('][').slice(-2);
secStr[0] = +secStr[0] +1; 
console.log(firstStr.concat(secStr).join(']['));

http://jsfiddle.net/3TuHg/ http://jsfiddle.net/3TuHg/

or like this 或像这样

var name = 'field[subform][0][subsubform][2][name]';
var str = name.split('][');
str[str.length - 2] = +str[str.length - 2] + 1;
str = str.join('][');
console.log(str);

http://jsfiddle.net/NsGvv/ http://jsfiddle.net/NsGvv/

Using indexOf and substr . 使用indexOfsubstr

The following code gets the first part of the string before the number, the number, and the string after the number. 以下代码获取数字前的字符串的第一部分,数字和数字后的字符串。 Then add 1 to the number and concat everything. 然后在数字上加1并合并所有内容。

var string = "field[subform][0][subsubform][2][name]",
    beg = string.indexOf("subsubform][") + 12,
    end = string.indexOf("]", beg);
string = string.substr(0, beg) + (parseInt(string.substr(beg, end)) + 1) + string.substr(end);

demo 演示

Regular expression fun. 正则表达式的乐趣。 Matches a pattern [number][string]end Of line, reads the number, adds one, joins other part of match, and sets the new name. 匹配模式[number] [string] end Of行,读取数字,加一个,加入匹配的另一部分,并设置新名称。

$(tr).find("input").prop("name", function() {
    return this.name.replace(
        /\[(\d+)(\]\[[^[]+]$)/,
        function (a,b,c) { 
            return "[" + (parseInt(b,10)+1) + "]" +  c;
        }
    )
});

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

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