我在使用正则表达式时遇到了麻烦。
我想替换所有出现的 myData=xxxx&
xxxx 可以更改,但总是以 &
结尾,除了最后一次出现,当它是 myData= xxx
。
var data = "the text myData=data1& and &myData=otherData& and end myData=endofstring"
data.replace(/myData=.*?&/g,'newData');
它返回:
the text newData and &newData and end myData=endofstring
哪个是正确的,但我如何检测到最后一个?
最佳答案
两件事:
您需要将
replace
的结果分配到某处,而您在问题的代码中没有这样做您可以使用替代 (
|
) 来匹配&
或字符串结尾
所以:
var data = "the text myData=data1& and &myData=otherData& and end myData=endofstring"
data = data.replace(/myData=.*?(?:&|$)/g,'newData');
// ^^^^^^^-- 1 ^^^^^^^-- 2
console.log(data);
请注意使用非捕获组 ((?:...)
) 来限制交替的范围。
关于javascript - 正则表达式查找字符串结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38481014/