查找并替换字符串中第[n]个[括号内]表达式的出现 [英] Find and replace nth occurrence of [bracketed] expression in string

查看:93
本文介绍了查找并替换字符串中第[n]个[括号内]表达式的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我需要使用JavaScript no更改方括号内的值他们所处的位置
我尝试使用以下正则表达式来匹配方括号之间的值:

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

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

但这符合所有匹配,我需要做的是以某种方式查找并替换第n个匹配项。

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

或者,如果有另一种方法可以在不使用正则表达式的情况下查找并替换方括号内的值,那么我就会全力以赴。

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

在此先感谢

解决

这个最终代码如下:

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;
    }));
});


推荐答案

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

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.

以下示例将替换第二个参数HELLO,WORLD中的L与M。

The following example will replace the second "L" in "HELLO, WORLD" with "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!";

请参阅MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

这篇关于查找并替换字符串中第[n]个[括号内]表达式的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆