Javascript get URL parameter that starts with a specific string

2.9k views Asked by At

With javascript, I'd like to return any url parameter(s) that start with Loc- as an array. Is there a regex that would return this, or an option to get all url parameters, then loop through the results?

Example: 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

3

There are 3 answers

0
Mirko Vukušić On BEST ANSWER

You can use window.location.search to get all parameters after (and including ?) from 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]})
0
gmiley On

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;
}
0
user2314737 On

Use URLSearchparams

The URLSearchParams interface defines utility methods to work with the query string of a 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));
  }
}