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

在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=([^\&].*)\&/) // 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