I am working on a web-application and would like to know, how can I get query string value in javascript (possible using jquery, or with plain javascript), I don't want to increase page load time by adding an extra plugin, a demo code example would work.
thanks
You can get query string data in javascript, without jquery using the function below
var querystring = (function(a) { if (a == "") return {}; var b = {}; for (var i = 0; i < a.length; ++i) { var p=a[i].split('=', 2); if (p.length == 1) b[p[0]] = ""; else b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " ")); } return b; })(window.location.search.substr(1).split('&'));
to use the above function, suppose your query string parameter is ?id=133&value=query+string+in+javascript
, to get these values you can run function like this:
querystring["id"] //133 querystring["value"] // query string in javascript querystring["Nothing"] //undefined
function getQueryString() { 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; }
If you have URL like this
http://demo.com/?id=123&value=SomeValue
If will return
{ "id" : "123", "value" : "SomeValue" }
Or you can get it by using function
var id= getQueryString()["id"];
Take a look at this solution if you want it in PHP-javascript, as per the comment on facebook here
Code for it:
var $_GET = (function(){
var g, r = {}, s = location.search.substr(1).split("&");
for (var i = 0; i < s.length; i++)
if ((g = s[i].split("=")).length)
r[decodeURI(g[0])] = decodeURI(g[1] || "");
return r;
})();
console.log($_GET);
// 1st: ?d --> is valid query!
// 2nd: ?d= --> same as above
// 3rd: ?a[]=d&a[]=4 --> don't even try bro, use post for that xD
Get Query string value using ES6
getQueryStringParams = query => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
let [key, value] = param.split('=');
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
return params;
}, {}
)
: {}
};
console.log( getQueryStringParams("https://jsfiddle.net/?testing=123&hello=world"));
//output
//{
// hello: "world",
// https://jsfiddle.net/?testing: "123"
//}
//
Source: How to get query string from url using jQuery or Javascript?
Thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly