我有一个元素的标识符,如下所示:
form_book_1_2_3
我想要的是用其他值替换此标识符中的第二个数字。我将函数“匹配”与以下正则表达式一起使用:
var regexp = /\d_(\d)_\d/;
但它返回包含
的数组[1_2_3, 2]
因此,当我尝试使用函数“replace”时,它实际上替换了“1_2_3”字符串,而不仅仅是“2”。我不明白如何指向替换函数中的第二个匹配元素。或者我的正则表达式有误?
最佳答案
replace
函数将替换整个匹配的字符串,而不仅仅是特定的捕获组。简单的解决方案是捕获字符串中您不想修改的部分,并将它们用作替换模式中的引用,例如:
"form_book_1_2_3".replace(/(\d)_\d_(\d)/, "$1_X_$2"); // "form_book_1_X_3"
作为引用,替换模式的完整语法是(来自 MDN):
$$
— Inserts a "$".$&
— Inserts the matched substring.$`
— Inserts the portion of the string that precedes the matched substring.$'
— Inserts the portion of the string that follows the matched substring.$<em>n</em>
or$<em>nn</em>
— Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was aRegExp
object.
或者,您可以使用函数来实现相同的目标,如下所示:
var replacer = function(match, a, b) { return a + "_X_" + b; };
"form_book_1_2_3".replace(/(\d)_\d_(\d)/, replacer); // "form_book_1_X_3"
关于javascript - JS用正则表达式替换数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24834072/