简体   繁体   中英

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 .

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

which is correct, but how can I detect the last one?

Two things:

  1. You need to assign the result of replace somewhere, which you're not doing in your question's code

  2. 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM