我试图交换我在JavaScript中找到并存储的两个字符串:
searchPattern = new RegExp ("(this)\\D{0,2}(that)", "gi");
var groupOneMatches = [];
var groupTwoMatches = [];
var text = "this that test string this: that";
text = text.replace(searchPattern, function (match, $1, $2) {
groupOneMatches.push($1);
groupTwoMatches.push($2);
});
alert(text);
答案 0 :(得分:0)
text
将始终显示为原始字符串,因为您从未为其设置新值:
text = text.replace(...)
答案 1 :(得分:0)
.replace
将使用由.replace
的第二个参数确定的字符串替换正则表达式的每个匹配项。如果要插入新的子串以替换旧的子串,则该函数需要返回一个字符串。像这样:
var searchPattern = new RegExp ("(this)(\\D{0,2})(that)", "gi");
var text = "this that test string this: that";
text = text.replace(searchPattern, function (match, $1, $2, $3) {
return $3 + $2 + $1;
});
至少,我认为这是你想要的,但它不是很清楚。