javascript 查找并替换字符串中第 n 次出现的 [括号内] 表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10584748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:21:10  来源:igfitidea点击:

Find and replace nth occurrence of [bracketed] expression in string

javascriptjqueryhtmlregexstring

提问by DJ Mosca

I have a form where the name attributes get updated, but the problem is im using multidimensional values as follows:

我有一个名称属性得到更新的表单,但问题是我使用的多维值如下:

<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...

I need to change the value within the square brackets with JavaScript no matter what positionthey are in. I have tried using the following regular expression to match the value between the square brackets:

无论它们处于什么位置,我都需要使用JavaScript 更改方括号内的值。我尝试使用以下正则表达式来匹配方括号之间的值:

/(?<=\[)[^\]]*(?=\])/g

but this matches all occurrences, and what I need to do is somehow find and replace the nth occurrence.

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

Or if there is another way to find and replace the values within the square brackets without using regular expressions I'm all ears.

或者,如果有另一种方法可以在不使用正则表达式的情况下查找和替换方括号内的值,我全都听着。

Thanks in advance

提前致谢

Resolved

解决

This final code is as follows:

最终代码如下:

$('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;
    }));
});

回答by Vivian River

Here is another possible solution. You can pass the string.replace function a function to determine what the replacement value should be. The function will be passed three arguments. The first argument is the matching text, the second argument is the position within the original string, and the third argument is the original string.

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

The following example will replace the second "L" in "HELLO, WORLD" with "M".

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

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!";

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

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

回答by raina77ow

The approach given in the accepted answer is concise and solid, but it has a drawback: if there's a big string with a lot of appearances of the given substring, it will be scanned till the end - even if one has to replace only at the beginning. The alternative would be using 'exec', then breaking off the chain right after the replacement is done:

接受的答案中给出的方法简洁而可靠,但它有一个缺点:如果有一个给定子字符串出现很多次的大字符串,它将被扫描到最后 - 即使一个人只需要在开始。另一种方法是使用“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) );

回答by strah

If I understand the question correctly the RegExp shown below should do:

如果我正确理解了这个问题,下面显示的 RegExp 应该做:

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/

演示在这里:http: //jsfiddle.net/EUcdX/