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
Parse GetVars With JavaScript
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
Snippets Manager replied on Thu, 2009/01/22 - 10:42am
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
Snippets Manager replied on Mon, 2007/10/22 - 5:33am
Snippets Manager replied on Mon, 2007/10/22 - 5:33am
/* 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