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).
11 comments :
Wouldn't it be this?
var name = nvPair[0];
var value = nvPair[1];
Yep, you're right! Thanks for the bug catch!
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
It works fine! I translate the article in italian in my tech blog
Rahul says:
Great!!It worked.I had to retrive Values from URL and desired values were in my JS.
how to parse URLs in JS you can find here
Very good, simple & effective, used this on my site, saved me some time...
thanks
Great, I was wondering how to do that. To put the name-value pairs into a global namespace, you can do:
(before the function declaration)
window.urlVars = new Object();
(and then within the loop)
window.urlVars[name] = value;
You can build your own javascript library that does this at http://jpaq.org/. For instance, if you are trying to get the "name" paramater, you can access it via the jPaq.GET["name"] variable. When you download this build, you also get two other useful URI functions.
Here's some code which can be run at page startup which will create a map of the URL args. It does not handle same-named args with an array suffix ("[]") like PHP does, but could easily be expanded to do so...
var MyApp = {
urlArgs:{}
};
MyApp.processUrlArgs = function() {
this.urlArgs = {};
var str = window.location.search ? window.location.search.substring(1) : false;
if( ! str ) return;
var sp = str.split(/&+/);
var rx = /^([^=]+)(=(.+))?/;
var k, v, i, m;
for( i in sp ) {
m = rx.exec( sp[i] );
if( ! m ) continue;
this.urlArgs[decodeURIComponent(m[1])] = decodeURIComponent(m[3]);
}
};
hermes belt
nike react
yeezy shoes
yeezy 500
air max 2017
moncler
supreme
golden goose
yeezy boost 350 v2
cheap jordans
Post a Comment