Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Parse GetVars with JavaScript (See related posts)

There are many examples of how to parse get vars client side around, but most of them are using arrays and take much more lines of code and ram then nescesary. This one gives an elegant way to get values of given get parameters:

/* javascript */
String.prototype.get = function(p){
  return(this.match(new RegExp("[?|&]?" + p + "=([^&]*)"))[1]);
}

/* test: yourfile.html?test=test234 alerts: test234 */
alert(window.location.search.get('test'));

Comments on this post

pyrou posts on Oct 22, 2007 at 05:49
You got an error if try getting an undefined var

this looks better :) thanks for your snippet.. useful for me ;)

/* javascript */
String.prototype.get = function(p){
    return (match = this.match(new RegExp("[?|&]?" + p + "=([^&]*)"))) ? match[1] : false;
}

// window.location = ?test1=var1&test2 

alert(window.location.search.get('test1')); // "var1"
alert(window.location.search.get('test2')); // ""  (null)
alert(window.location.search.get('test3')); // false
pyrou posts on Oct 22, 2007 at 05:51
test case is ?test1=var1&test2= instead ?test1=var1&test2 ;)
featurelover posts on Oct 22, 2007 at 16:05
@pyrou thanks for the improvement ;)

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts