Skip to content

Instantly share code, notes, and snippets.

@naheedakhtar
Created August 4, 2012 21:12
Show Gist options
  • Save naheedakhtar/3259979 to your computer and use it in GitHub Desktop.
Save naheedakhtar/3259979 to your computer and use it in GitHub Desktop.
URL Parse get parameter javascript
You don't need jQuery for that purpose you can use the pure JavaScript:
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
====================
Some of the solutions posted here are inefficient. Repeating the regular expression search every time the script needs to access a parameter is completely unnecessary, one single function to split up the parameters into an associative-array style object is enough. If you're not working with the HTML 5 History API, this is only necessary once per page load. The other suggestions here also fail to decode the URL correctly.
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Example querystring:
?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty
Result:
urlParams = {
enc: " Hello ",
i: "main",
mode: "front",
sid: "de8d49b78a85a322c4155015fdce22c4",
empty: ""
}
alert(urlParams["mode"]);
// -> "front"
alert("empty" in urlParams);
// -> true
This could easily be improved upon to handle array-style query strings too. An example of this is here, but since array-style parameters aren't defined in RFC 3986 I won't pollute this answer with the source code.
Also, as pointed out in the comments, ; is a legal delimiter for key=value pairs. It would require a more complicated regex to handle ; or &, which I think is unnecessary because it's rare that ; is used and I would say even more unlikely that both would be used. If you need to support ; instead of &, just swap them in the regex.
If you're using a server-side preprocessing language, you might want to use its native JSON functions to do the heavy lifting for you. For example, in PHP you can write:
<script>var urlParams = <?php echo json_encode($_GET, JSON_HEX_TAG);?>;</script>
=============
Improved version of Artem Barger's answer:
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
For more information on improvement see: http://james.padolsey.com/javascript/bujs-1-getparameterbynam
=============
Without jQuery
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
With an URL like ?topic=123&name=query+string, the following will return:
qs["topic"]; // 123
qs["name"]; // query string
qs["nothere"]; // undefined (object)
Google method
Tearing Google's code I found the method they use: getUrlParameters
function (b) {
var c = typeof b === "undefined";
if (a !== h && c) return a;
for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {
var l = b[f][p]("=");
if (l !== -1) {
var q = b[f][I](0, l),
l = b[f][I](l + 1),
l = l[Ca](/\+/g, " ");
try {
d[q] = e(l)
} catch (A) {}
}
}
c && (a = d);
return d
}
It is obfuscated, but it is understandable.
===========
My method as a jQuery plugin
(function($) {
$.QueryString = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'))
})(jQuery);
Usage
$.QueryString["param"]
=============
Keep it simple:
function qs(key) {
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];
}
return vars[key];
}
Call it from anywhere in the JavaScript code:
var result = qs['someKey'];
@naheedakhtar
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment