How to get query string from url using jQuery or Javascript?


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?


Asked by:- bhanu
2
: 3044 At:- 5/24/2021 6:45:46 AM
jQuery javascript jquery get query string







2 Answers
profileImage Answered by:- vikas_jk

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.

Using ES6

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.

2
At:- 5/24/2021 8:05:20 AM Updated at:- 9/20/2022 1:53:08 AM
Thanks for useful answer, I have tried jQuery based solution and it is working as needed. 0
By : bhanu - at :- 5/24/2021 10:14:14 AM


profileImage Answered by:- jon

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.

0
At:- 12/12/2022 4:08:35 PM Updated at:- 12/12/2022 4:09:44 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use