I would like to extract characters from mid string with optional end character. If the optional end character is not found, extract until end of string. The first characters are S= and the last optional character is &.
Example #1:
"rilaS=testingabc"
should extract:
"testingabc"
Example #2:
"rilaS=testing123&thistest"
should extract:
"testing123"
This is what I have so far (Javascript):
var Str = "rilaS=testing123&thistest";
var tmpStr = Str.match("S=(.*)[\&]{0,1}");
var newStr = tmpStr[1];
alert(newStr);
But it does not detect that the end should be the ampersand (if found). Thank you before hand.
Answer (By ggorlen)
var Str = "rilaS=testing123&thistest";
var tmpStr = Str.match("S=([^&]*)");
var newStr = tmpStr[1];
alert(newStr);
You may use /S=([^&]*)/
to grab from an S=
to end of line or &
:
["rilaS=testingabc", "rilaS=testing123&thistest"].forEach(s => console.log(s.match(/S=([^&]*)/)[1]) );
Just in case you are wondering why your original regex didn't work: the problem is that the (.*) pattern is greedy - meaning it will happily slurp up anything, including &, and not leave it for for later items to match. This is why you want the "not &" - it will match up to, but not including the &.
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.