[英]regular expression find end of string
I have troubles with a regular expression. 我有一个正则表达式的麻烦。
I want to replace all ocurrences of myData=xxxx&
xxxx can change, but always ends with &
, except the last ocurrence, when it is myData=xxx
. 我想替换
myData=xxxx&
xxxx的所有发生变化,但总是以&
结束,除了最后一次发生,当它是myData=xxx
。
var data = "the text myData=data1& and &myData=otherData& and end myData=endofstring"
data.replace(/myData=.*?&/g,'newData');
it returns : 它返回:
the text newData and &newData and end myData=endofstring
文本newData和&newData并结束myData = endofstring
which is correct, but how can I detect the last one? 这是正确的,但我怎么能检测到最后一个?
Two things: 两件事情:
You need to assign the result of replace
somewhere, which you're not doing in your question's code 你需要在某个地方分配
replace
结果,而你在问题的代码中没有这样做
You can use an alternation ( |
) to match either &
or end of string 您可以使用替换 (
|
)来匹配字符串的&
或结尾
So: 所以:
var data = "the text myData=data1& and &myData=otherData& and end myData=endofstring" data = data.replace(/myData=.*?(?:&|$)/g,'newData'); // ^^^^^^^-- 1 ^^^^^^^-- 2 console.log(data);
Note the use of a non-capturing group ( (?:...)
), to limit the scope of the alternation. 注意使用非捕获组(
(?:...)
)来限制交替的范围。
What about : 关于什么 :
data="myData=abc& and linked with something else";
data.replace(/myData=.*?&/g,'newData');
https://jsfiddle.net/ob8c2j9v/ https://jsfiddle.net/ob8c2j9v/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.