Javascript 用正则表达式取一些字符串
在Javascript中,我试图读取Javascript 用正则表达式取一些字符串,javascript,regex,Javascript,Regex,在Javascript中,我试图读取window.location.search。此变量的值可能类似于?ref=somestring&read=1或?read=1&ref=somestring或只是?ref=somestring 如何仅从变量中提取ref=somestring 到目前为止,我尝试了以下正则表达式: ref.match(/ref=([^\&].*)\&/) // works when ?ref=somestring&read=1 ref.match(/ref
window.location.search
。此变量的值可能类似于?ref=somestring&read=1
或?read=1&ref=somestring
或只是?ref=somestring
如何仅从变量中提取ref=somestring
到目前为止,我尝试了以下正则表达式:
ref.match(/ref=([^\&].*)\&/) // works when ?ref=somestring&read=1
ref.match(/ref=([^\&].*)\&/) // not working when only ?ref=somestring
ref.match(/ref=([^\&].*)\&?/) // works when ?ref=somestring
ref.match(/ref=([^\&].*)\&?/) // works but took all part if ?ref=somestring&read=1
您可以使用:
var m = (ref.match(/[?&](ref[^&]+)/) || ['', ''])[1];
此正则表达式首先匹配:?
或&
后跟文本ref=
,后跟[^&]+
和组中的组ref[^&]+
ref.match(/(ref=[^\&]*)/) //for ref=somestring
或
ref.match(/ref=([^\&]*)/) //for somestring