get URL parameters in javascript
posted on April 20, 2014, 6:45 pm in
Easily get url parameters using vanilla JavaScript.
The Code
Getting a single param:
var url = window.location.href.toLowerCase();
var getURLParam = function( name , url ) {
url = url.split( '#');
url = url[0];
url = url.split( name + '=');
return decodeURIComponent( (url[1] || '-1').split('&')[0] );
};
or get all parameters as an object:
var url = window.location.href.toLowerCase();
var getAllURLParams = function(url) {
url = url.split('#');
url = url[0];
url = url.split('?');
url = url[1].split('&');
var temp = {},
split;
for (var x = 0; x < url.length; x++) {
split = url[x].split('=');
temp[split[0]] = decodeURIComponent(split[1]);
}
return temp;
};
Tests
console.log(getURLParam('flag', "http://domain.com/?id=879879&flag=0909&hhu=") == "0909");
console.log(getURLParam('flag', "http://domain.com/?id=879879&flag=0909&hhu=#test") == "0909");
console.log(getURLParam('id', "http://domain.com/?id=&flag=0909&hhu=") == "");
console.log(getURLParam('id', "http://domain.com/?id=12345") == "12345");
console.log(getURLParam('hhu', "http://domain.com/?id=879879&flag=0909&hhu=") == "-1");
console.log(getURLParam('x', "http://www.domain.com/index.php?x=x1&x=x2&x=x3") == "x1");
console.log(getURLParam('c', "www.domain.com/t.html?a=1&b=3&c=m2-m3-m4-m5") == "m2-m3-m4-m5");
console.log(getURLParam('enc', "?i=main&mode=front&sid=de8d49b78ae22c4&enc=+Hello%20&empty") == "+Hello ");
console.log(getURLParam('empty',"?i=main&mode=front&sid=de8d4dce22c4&enc=+Hello%20&empty") == "-1");
console.log(getAllURLParams("http://domain.com/?id=879879&flag=0909&hhu="));
console.log(getAllURLParams("http://domain.com/?id=879879&flag=0909&hhu=#test"));