Get Query String Parameters using Javascript

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we will use Javascript to get the query string parameters from the URL.  Suppose we have an URL like this …

url with query string param

url with query string param

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 …

javascript getting search portion

javascript getting search portion

will get the search portion of the URL without the question mark as you can see as output to browser console…

browser console shows extracted search portion

browser console shows extracted search portion

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…

split params

split params

We got the array of parameters looking like this …

array of parameters

array of parameters

For each of these strings, we split them on the equal sign …

go through each param

go through each param

And output the key value pairs to console …

key value pairs

key value pairs

We can make this piece of code more re-usable by making it into a function…

make into function

make into function