I will be receiving the following string format from an AJAX call: [link= https://www.w3schools.com text=here]
I need to extract the values after "link=" and the value after "text=" so, my ideal output would assign " https://www.w3schools.com " to a variable and then "here" to a variable as shown in the code below. The values for "link=" and "text=" will change.
I've tried playing around with regex matching and using .split in Javascript, but I can't get the intended values just right.
var str = "[link=https://www.w3schools.com text=here]";
var link = str.match(/link=(.*)/)[1]; //gets the link but includes rest of string
var linkText = str.match(/text=(.*)/)[1]; //gets "here" plus the closing bracket
add "\\s" and "]" in your pattern, Try this
var str = "[link=https://www.w3schools.com text=here]"; var link = str.match(/link=(.*)\\s/)[1]; //gets the link but includes rest of string var linkText = str.match(/text=(.*)]/)[1]; console.log(link); console.log(linkText);
You may use
var str = "[link=https://www.w3schools.com text=here]"; var m, res=[], rx=/(?:^|[\\s[])(link|text)=([^\\][\\s]*)/g; while (m = rx.exec(str)) { console.log(m[1], "=", m[2]); }
The regex is
/(?:^|[\s[])(link|text)=([^\][\s]*)/
See the regex demo .
Details
(?:^|[\\s[])
- start of string or a whitespace or [
(link|text)
- Group 1: link or text words =
- a =
symbol ([^\\][\\s]*)
- Group 2: any 0+ chars other than [
, ]
and whitespace.
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.