[英]Need to extract values from string in Javascript between words and characters
I will be receiving the following string format from an AJAX call: [link= https://www.w3schools.com text=here] 我将从AJAX呼叫中接收以下字符串格式:[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. 我需要提取“ link =”之后的值,然后提取“ text =”之后的值,所以,我的理想输出是将“ https://www.w3schools.com ”分配给变量,然后将“ here”分配给变量,如图所示在下面的代码中。 The values for "link=" and "text=" will change.
“ link =”和“ text =”的值将更改。
I've tried playing around with regex matching and using .split in Javascript, but I can't get the intended values just right. 我已经尝试过使用正则表达式匹配并在Javascript中使用.split,但是我无法获得正确的预期值。
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 在您的模式中添加“ \\ s”和“]” ,试试看
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 . 参见regex演示 。
Details 细节
(?:^|[\\s[])
- start of string or a whitespace or [
(?:^|[\\s[])
-字符串或空白或[
(link|text)
- Group 1: link or text words (link|text)
-第1组:链接或文字 =
- a =
symbol =
-a =
符号 ([^\\][\\s]*)
- Group 2: any 0+ chars other than [
, ]
and whitespace. ([^\\][\\s]*)
-组2:除[
, ]
和空格以外的任何0+个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.