public
Last active

Read URL GET variable

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Given a query string "?to=email&why=because&first=John&Last=smith"
// getUrlVar("to") will return "email"
// getUrlVar("last") will return "smith"
 
// Slightly more concise and improved version based on http://www.jquery4u.com/snippets/url-parameters-jquery/
function getUrlVar(key){
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && unescape(result[1]) || "";
}
 
// To convert it to a jQuery plug-in, you could try something like this:
(function($){
$.getUrlVar = function(key){
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && unescape(result[1]) || "";
};
})(jQuery);

If you would like to get all key/value pairs at once, use a variation of this function by Ashley Ford: http://papermashup.com/read-url-get-variables-withjavascript/

Nice elegant, thanks.

I replaced unescape with decodeURIComponent to support utf-8 htmlentities characters.

Wonderful. Thank you!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.