Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 685
cucuru Avatar asked Nov 03 '25 22:11

cucuru


1 Answers

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.

like image 145
T.J. Crowder Avatar answered Nov 06 '25 22:11

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!