Parsing URL Variables With JavaScript

URL variables are variables that are passed in as part of the address(URL)of a page. Typically they are a series of name-value pairs that are separated by an ampersand and are delineated from the page's URL by a question mark.

Normally you grab these vars with a backend language like JSP or PHP and act on them there. There are times though when you either don't have access to a backend language or just need to handle these parameters via JavaScript. Here's how.


var searchString = document.location.search;

// strip off the leading '?'
searchString = searchString.substring(1);

var nvPairs = searchString.split("&");

for (i = 0; i < nvPairs.length; i++)
{
     var nvPair = nvPairs[i].split("=");
     var name = nvPair[0];
     var value = nvPair[1];
}

First we strip off the questionmark separating the URL of the page from its parameter list. Then we create an array of all the name-value pairs. Lastly, we loop through this array and extract each name and value. (You would insert conditional logic to handle these name-value pairs at that point).

5 comments:

Joseph said...

Wouldn't it be this?

var name = nvPair[0];
var value = nvPair[1];

HUWebDev said...

Yep, you're right! Thanks for the bug catch!

Larry said...

This function works great! I have created (using your code) a function that retrieves the value of a passed in parm name. Every thing works well except I also need to strip out any URL special character replacements (spaces, *, etc.). Do you have any suggestions for this?

Thanks

Alessio said...

It works fine! I translate the article in italian in my tech blog

Anonymous said...

Rahul says:
Great!!It worked.I had to retrive Values from URL and desired values were in my JS.