Javascript Javascript正则表达式多重匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7954022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Regular Expression multiple match
提问by user815460
I'm trying to use javascript to do a regular expression on a url (window.location.href) that has query string parameters and cannot figure out how to do it. In my case, there is a query string parameter can repeat itself; for example "quality", so here I'm trying to match "quality=" to get an array with the 4 values (tall, dark, green eyes, handsome):
我正在尝试使用 javascript 在具有查询字符串参数的 url (window.location.href) 上执行正则表达式,但无法弄清楚如何去做。就我而言,有一个查询字符串参数可以重复;例如“质量”,所以在这里我尝试匹配“质量=”以获取具有 4 个值(高、黑、绿眼睛、英俊)的数组:
http://www.acme.com/default.html?id=27&quality=tall&quality=dark&quality=green eyes&quality=handsome
回答by alex
回答by toinetoine
A slight variation of @alex 's answer for those who want to be able to match non-predetermined parameter names in the url.
对于那些希望能够在 url 中匹配非预定参数名称的人,@alex 的答案略有变化。
var getUrlValue = function(name, url) {
var valuesRegex = new RegExp('(?:^|[&;?])' + name + '=([^&;?]+)', 'g')
var matches;
var values = [];
while (matches = valuesRegex.exec(url)) {
values.push(decodeURIComponent(matches[1]));
}
return values;
}
var url = 'http://www.somedomain.com?id=12&names=bill&names=bob&names=sally';
// ["bill", "bob", "sally"]
var results = getUrlValue('names', url);