简体   繁体   English

Javascript获取以特定字符串开头的URL参数

[英]Javascript get URL parameter that starts with a specific string

With javascript, I'd like to return any url parameter(s) that start with Loc- as an array. 使用javascript,我想将以Loc-开头的所有url参数作为数组返回。 Is there a regex that would return this, or an option to get all url parameters, then loop through the results? 是否有将返回此值的正则表达式,还是获取所有url参数,然后遍历结果的选项?

Example: www.domain.com/?Loc-chicago=test 例如:www.domain.com/?Loc-chicago = test

If two are present in the url, I need to get both, such as: 如果网址中存在两个,则需要同时获取两个,例如:

www.domain.com/?Loc-chicago=test&Loc-seattle=test2 www.domain.com/?Loc-chicago=test&Loc-seattle=test2

You can use window.location.search to get all parameters after (and including ? ) from url. 您可以使用window.location.search从url之后(包括? )获取所有参数。 Then it's just a matter of looping through each parameter to check if it match. 然后,只需遍历每个参数以检查其是否匹配即可。

Not sure what kind of array you expect for result but here is very rough and basic example to output only matched values in array: 不确定要获得哪种数组,但下面是一个非常粗糙且基本的示例,仅在数组中输出匹配的值:

var query = window.location.search.substring(1);
var qsvars = query.split("&");
var matched = qsvars.filter(function(qsvar){return qsvar.substring(0,4) === 'Loc-'});
matched.map(function(match){ return match.split("=")[1]})

Use URLSearchparams 使用URLSearchparams

The URLSearchParams interface defines utility methods to work with the query string of a URL. URLSearchParams接口定义实用程序方法以与URL的查询字符串一起使用。

 var url = new URL("http://" + "www.domain.com/?Loc-chicago=test&NotLoc=test1&Loc-seattle=test2"); var paramsString = url.search; var searchParams = new URLSearchParams(paramsString); for (var key of searchParams.keys()) { if (key.startsWith("Loc-")) { console.log(key, searchParams.get(key)); } } 

Here is a function you can use that accepts a parameter for what you are looking for the parameter to start with: 这是您可以使用的函数,该函数接受您要查找的参数开头的参数:

function getUrlParameters(var matchVal) {
    var vars = [];
    var qstring = window.location.search;

    if (qstring) {
        var items = qstring.slice(1).split('&');
        for (var i = 0; i < items.length; i++) {
            var parmset = items[i].split('=');
            if(parmset[0].startsWith(matchVal)
                vars[parmset[0]] = parmset[1];
        }
    }
    return vars;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM