![](/img/trans.png)
[英]Javascript: How to extract english words or Chinese characters from a string?
[英]Need to extract values from string in Javascript between words and characters
我將從AJAX呼叫中接收以下字符串格式:[link = https://www.w3schools.com text = here]
我需要提取“ link =”之后的值,然后提取“ text =”之后的值,所以,我的理想輸出是將“ https://www.w3schools.com ”分配給變量,然后將“ here”分配給變量,如圖所示在下面的代碼中。 “ link =”和“ text =”的值將更改。
我已經嘗試過使用正則表達式匹配並在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
在您的模式中添加“ \\ 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);
您可以使用
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]); }
正則表達式是
/(?:^|[\s[])(link|text)=([^\][\s]*)/
參見regex演示 。
細節
(?:^|[\\s[])
-字符串或空白或[
(link|text)
-第1組:鏈接或文字 =
-a =
符號 ([^\\][\\s]*)
-組2:除[
, ]
和空格以外的任何0+個字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.