Search code examples
javascripturl-parametersstartswith

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. 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


Solution

  • 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]})