Javascript: Get Query String (Easy)
This tutorial assumes that you already know what a query string is. If you are looking for a way to get the query string values and assign to a variable, then check the following block of codes.
Do note that this is only pure Javascript. No need for plugins or libraries.
var queryString = {};
var params = location.search.substr(1).split('&');
params.forEach(function( param ){
    [name, value] = param.split('=');
    queryString[name] = decodeURIComponent((value).replace(/\+/g, '%20'));
});
// check the output
console.log(queryString);In the above code, we use
location.search which is the way to get the query string. The result of location.search. would be a string type like this:?key1=value1&key2=value2To get the desired result we want, we first remove the
'?' mark with .substr(1), then split the string with delimiter '&'The resulting array is then looped through using
.forEach(). For each array item we then split the string with delimeter '=' then assign the result name=key and value=value.We then stored this name and value to our
queryString variable for later use.
Comments
Post a Comment