Skip to content

Instantly share code, notes, and snippets.

@chrisveness
Created August 30, 2014 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisveness/d44b78eee957413943d9 to your computer and use it in GitHub Desktop.
Save chrisveness/d44b78eee957413943d9 to your computer and use it in GitHub Desktop.
Get query string argument (using split/for)
/**
* Returns specified argument from query string.
*
* @params {string} key - Argument to be returned.
* @returns {string} Value of key ('' for ?arg=, null for ?arg, undefined if not present).
*/
function getQueryArg(key) {
var srch = location.search.substring(1); // lose the initial '?'
var args = srch.split(/[&;]/); // list of field=value pairs
for (var i=0; i<args.length; i++) { // for each arg
var arg = args[i].split('='); // split at '='
if (arg[0] == key) { // arg we're looking for?
if (arg.length == 1) return null; // ?key without '='
return decodeURIComponent(arg[1].replace(/\+/g, ' '));
}
}
return undefined; // not found
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment