DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Parse GetVars With JavaScript

10.20.2007
| 6120 views |
  • submit to reddit
        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

Snippets Manager replied on Fri, 2010/06/25 - 4:02pm

Awesome guys! This resolved a couple of days frustration with using another window.location.search parsing solution which hung up in IE but not in Firefox and Chrome.

Snippets Manager replied on Thu, 2009/01/22 - 10:42am

I've tried to improve this even more by adding a cache: String.prototype.getvars = []; String.prototype.get = function(p){ if (this.getvars[p]) { return this.getvars[p]; } var match = this.match(new RegExp("[?|&]?" + p + "=([^&]*)")); return this.getvars[p] = (match) ? match[1] : false; }

Snippets Manager replied on Wed, 2007/10/17 - 3:54pm

@pyrou thanks for the improvement ;)

Snippets Manager replied on Mon, 2007/10/22 - 5:33am

test case is ?test1=var1&test2= instead ?test1=var1&test2 ;)

Snippets Manager replied on Mon, 2007/10/22 - 5:33am

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