2012-05-14 52 views
9

我在名称属性得到更新一种形式,但使用多维值如下问题IM:查找和替换[括号]表达的第n次出现在字符串

<input type="text" name="questions[0][question]" /> 
<input type="text" name="questions[0][order]" /> 
<input type="text" name="questions[0][active]" /> 
<input type="text" name="answers[0][1][answer]" /> 
<input type="text" name="answers[0][2][answer]" /> 
<input type="text" name="answers[0][3][answer]" /> 

<input type="text" name="questions[1][question]" /> 
<input type="text" name="questions[1][order]" /> 
<input type="text" name="questions[1][active]" /> 
etc... 

我需要改变。

/(?<=\[)[^\]]*(?=\])/g 
:方括号用JavaScript没有 无论他们是在什么位置内的值 我曾尝试使用下面的正则表达式匹配的方括号之间的值尝试

但这匹配所有事件,我需要做的是以某种方式找到并替换第n次出现。

或者,如果有另一种方法来查找和替换方括号内的值,而不使用正则表达式,我全是耳朵。

在此先感谢

解决

这最后的代码如下:

$('input', this).each(function(){ 
    var name = $(this).attr('name'); 
    var i = 0; 
    $(this).attr('name', name.replace(/\[.+?\]/g,function (match, pos, original) { 
    i++; 
    return (i == 1) ? "[THE REPLACED VALUE]" : match; 
    })); 
}); 
+0

我不是什么你试图做完全清楚!使用上面的示例可以显示预期的输出... – ManseUK

+0

欢迎使用StackOverflow。我发现这个问题没有得到太多的观点,所以我编辑了标题,清楚地反映了你所问的问题 - 如何找到并替换方括号中的第n个表达式。 –

回答

32

这是另一种可能的解决方案。您可以传递函数string.replace函数来确定替换值应该是什么。该函数将传递三个参数。第一个参数是匹配的文本,第二个参数是原始字符串中的位置,第三个参数是原始字符串。

以下示例将用“M”替换“HELLO,WORLD”中的第二个“L”。

var s = "HELLO, WORLD!"; 
var nth = 0; 
s = s.replace(/L/g, function (match, i, original) { 
    nth++; 
    return (nth === 2) ? "M" : match; 
}); 
alert(s); // "HELMO, WORLD!"; 

见MDN:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

+0

谢谢Daniel,这个工作很完美。我不知道替换函数有一个回调函数。 –

+0

如果这回答了您的问题,请点击此答案旁边的复选标记将其标记为接受的答案。 –

+0

正是我需要的,谢谢! – SpartaSixZero

0

如果我明白这个问题正确如下所示的正则表达式应该做的:

var patt = /<input.*?(\[(\d)\])(\[(\d)\]){0,1}.*/g 
var res = patt.exec(' <input type="text" name="questions[0][1][question]" />'); 

alert('First number: ' + res[2] + "\nSecond number: " + res[4]); 

Demo here:http://jsfiddle.net/EUcdX/

0

在接受的答案给出的方法是简洁和固体,但它有一个缺点:如果有一个大的字符串有很多给定的子串的出现,它会扫描直到结束 - 即使只有在开始时才需要更换。另一种方法是使用“EXEC”,然后掰链置换完成后右:

function replaceNthOccurence(source, pattern, replacement, n) { 
 
    var substr = ''; 
 
    while (substr = pattern.exec(source)) { 
 
    if (--n === 0) { 
 
     source = source.slice(0, substr.index) + replacement + source.slice(pattern.lastIndex); 
 
     break; 
 
    } 
 
    } 
 
    return source; 
 
} 
 

 
console.log(replaceNthOccurence('bla_111_bla_222_bla_333', /\d+/g, '1st', 1)); 
 
console.log(replaceNthOccurence('bla_111_bla_222_bla_333', /\d+/g, '2nd', 2)); 
 
console.log(replaceNthOccurence('bla_111_bla_222_bla_333', /\d+/g, '3rd', 3));

相关问题