![](/img/trans.png)
[英]Javascript regular expression to remove characters from the end of a string
[英]Javascript regular expression to extract characters from mid string with optional end character
我想從中間字符串中提取帶有可選結束字符的字符。 如果找不到可選的結束符,請提取到字符串末尾。 前一個字符為S =,最后一個可選字符為&。
范例1:
"rilaS=testingabc"
應該提取:
"testingabc"
范例2:
"rilaS=testing123&thistest"
應該提取:
"testing123"
到目前為止,這是我所擁有的(JavaScript):
var Str = "rilaS=testing123&thistest";
var tmpStr = Str.match("S=(.*)[\&]{0,1}");
var newStr = tmpStr[1];
alert(newStr);
但是它沒有檢測到結尾應該是“&”號(如果找到)。 先謝謝你。
答案(通過gorgoren)
var Str = "rilaS=testing123&thistest";
var tmpStr = Str.match("S=([^&]*)");
var newStr = tmpStr[1];
alert(newStr);
您可以使用/S=([^&]*)/
從S=
抓取到行尾或&
:
["rilaS=testingabc", "rilaS=testing123&thistest"].forEach(s => console.log(s.match(/S=([^&]*)/)[1]) );
以防萬一,您想知道為什么原來的正則表達式不起作用:問題是(。*)模式貪婪 -意味着它會愉快地吞噬包括&在內的所有內容,並且不留給以后的項目匹配。 這就是為什么您想要“ not&”的原因-它可以匹配,但不包括&。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.