Hello, I would like to fetch query string from url on page-load using jQuery or javascript, then how can I do it, suppose below is my website URL
https://www.example.com/?key=value
Then how can I easily fetch "key" using jQuery?
Using jQuery you can use .location
for QueryString
$( document ).ready(function() {
var QueryStrings = {};
$.each(document.location.search.substr(1).split('&'),function(c,q){
var i = q.split('=');
QueryStrings[i[0].toString()] = i[1].toString();
});
console.log(QueryStrings);
})
Using Plain Javascript:
You can use below function
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, " "));
}
console.log(b);
return b;
})(window.location.search.substr(1).split('&'));
If you already know "key" names, using above method, you can fetch value as
QueryString["keyName"];
try checking fiddle for this https://jsfiddle.net/hLoq3m6p/
You can check fiddle console for output. (Fiddle URL for main html is different so you can see the query string output in console)
It should work.
You can use the below ES6 based JS function
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;
}, {}
)
: {}
};
That's it.
Try checking proxy
which is
faster to get query string values in Javascript
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "some_key" in eg "https://yourdomain.com/?some_key=some_value"
let value = params.some_key; // "some_value"
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly