Read GET URL variables using JavaScript

1 min read
Support this website by purchasing prints of my photographs! Check them out here.
DEPRECATED: This post may no longer be relevant or contain industry best-practices.

Here is a function which will either build an associative array of the GET URL variables on the current page, or return the value of a specified GET variable in JavaScript:

function getUrlVar(requestedKey) {
 var vars = [], hash;
 var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
 for (var i = 0; i < hashes.length; i++) {
 hash = hashes[i].split('=');
 vars.push(hash[0]);
 vars[hash[0]] = hash[1];
 }
 if (typeof requestedKey == 'undefined') {
 return vars;
 } else {
 return vars[requestedKey];
 }
}

Usage:

var site_search = getUrlVar("site_search");
var all_vars = geturlVar();
var site_search_again = all_vars['site_search'];
Tags: #javascript
[画像:Thomas Hunter II Avatar]

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /