Get Query String Parameters using Javascript
In this tutorial, we will use Javascript to get the query string parameters from the URL. Suppose we have an URL like this …
with the query string parameter “id” and “type”. We want Javascript to retrieve the value of these two parameters.
This Javascript on the index.html page …
will get the search portion of the URL without the question mark as you can see as output to browser console…
This is because window.location.search will get the URL portion including the question mark. The substring starts extracting to the end of string starting at character index 1 and hence excludes the initial question mark character.
Now we split the searchString into an array called “params” using “&” as the delimiter…
We got the array of parameters looking like this …
For each of these strings, we split them on the equal sign …
And output the key value pairs to console …
We can make this piece of code more re-usable by making it into a function…