[英]javascript replace one of multiple regex matches
I'm making a script that reads a .txt file and puts it into a variable which looks like: 我正在制作一个读取.txt文件的脚本,并将其放入一个变量,如下所示:
myString = "blablabla [12], foo bar bar[2], bar foo[34], hello hello [95], wheres my sandwich [2745]";
I managed to generate an array that contains all the values between brackets, to do so I used this line of code: parameters = myString.match(/[^[]+(?=\\])/g);
我设法生成一个包含括号之间所有值的数组,为此我使用了这行代码: parameters = myString.match(/[^[]+(?=\\])/g);
So now I can easily get any of those values by calling parameters[n]
所以现在我可以通过调用parameters[n]
轻松获得任何这些值
All I want to do now is to change the value of one of those elements between [ ], and inject it back to the string, but I don't know how to do it. 我现在要做的就是在[]之间更改其中一个元素的值,并将其注入字符串,但我不知道该怎么做。 Of course if I use the following line: 当然,如果我使用以下行:
myString = myString.replace(/[^[]+(?=\])/g, "newValue");
All the elements will be replaced so I will end up with a string like blablabla [newValue], foo bar bar[newValue], bar foo[newValue], hello hello [newValue], wheres my sandwich [newValue]
所有元素都将被替换,所以我最终会得到一个字符串,如blablabla [newValue], foo bar bar[newValue], bar foo[newValue], hello hello [newValue], wheres my sandwich [newValue]
String.prototype.replace
accepts not only string, but also function as replacement. String.prototype.replace
不仅接受字符串,还接受替换。 If you pass a function, the return value of the function is used as replacement string. 如果传递函数,则函数的返回值将用作替换字符串。
Using that feature: 使用该功能:
var nth = 0;
myString.replace(/[^[]+(?=\])/g, function(match) {
// Change only the 2nd matched string.
return ++nth == 2 ? "newValue" : match;
});
// => "blablabla [12], foo bar bar[newValue], bar foo[34], hello hello [95],
// wheres my sandwich [2745]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.