0

i am using the following method to get parameter by name:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

and i was wondering how to change it to get parameter that contains some string for example, i want to get the parameter that contains the word "document" but the whole parameter name is not "document".

please advise, thanks.

4

2 回答 2

1

建议:

function getParameterByPartialName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&][^&#]*" + name + "[^=]*=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

但是,这将仅返回第一个匹配项,可能会有更多具有相似名称的参数。您可以返回所有匹配项的键值对数组。

于 2013-07-23T09:26:47.413 回答
1

像这样?

 val = location.search.match(/document.*?=([^&]*)/)[1]

虽然我宁愿使用一个函数将整个查询字符串转换为一个对象(比如这个),然后简单地应用一个过滤器:

params = urlParams()
ks = Object.keys(params).filter(function(k) { return k.indexOf("document") >= 0 })
if(ks)
   value = params[ks[0]];

这样,您可以轻松支持多个参数(如document1=foo&document2=bar)并避免丑陋的动态正则表达式构造。

在较旧的浏览器中,您可以使用它来代替 Object.keys/filter:

ks = []
for(var k in params)
     if(k.indexOf("document") >= 0)
        ks.push(k);
于 2013-07-23T09:24:09.467 回答