Learn how to get url parameter or all query string values with vanilla javascript.
We can pass different values with url as query string in the get request which is widely used for searching.
If you have googled something you may have noticed that google passes different query string in the url in order to get the search result.
https://www.google.com/search?q=ceaser+cipher+javascript&rlz=1C5CHFA_enIN855IN855&oq=ceaser+cipher+javascript&aqs=chrome..69i57.12963j0j1&sourceid=chrome&ie=UTF-8
The value after ?
is called query string. We will see how we can create a custom function in order to fetch url parameter in javascript.
Getting all query string values in javascript.
We will get the url parameters as a key value pair. In order to do that we will first the query string from the URL.
To do that we create a link and set the url as its href
and then get the search query.
let link = document.createElement('a'); link.href = url; let query = link.search.substring(1);
Next, we split the query string on &
to get the array of parameters with value.
Different parameters in the url are separated by &
.
let parameters = query.split('&');
Now as the key value are assigned using =
operator. We will split each element of the array on =
and store the key and value separately in an object.
We’ll run our value through decodeURIComponent() to get a proper string, and push the key and value to our object.
const vars = {}; for (let i = 0; i < parameters.length; i++) { let pair = parameters[i].split('='); vars[pair[0]] = decodeURIComponent(pair[1]); }
Finally, we’ll return the object of key/value pairs.
return vars;
Here is the complete code to get all the query strings from an url in javascript.
const getParams = function (url) { //Create a dummy link let link = document.createElement('a'); link.href = url; //Get the query string let query = link.search.substring(1); //Split the params let parameters = query.split('&'); //Object to store the key/value pair const vars = {}; //Get the key/value pair for (let i = 0; i < parameters.length; i++) { let pair = parameters[i].split('='); vars[pair[0]] = decodeURIComponent(pair[1]); } return vars; };
let url = 'https://learnersbucket.com?datastructure=linked%10list&algorithm=array'; console.log(getParams(url)); Output: Object { algorithm: "array", datastructure: "linkedlist" }
This works in all modern browsers, and back to at least IE6.