9

I want to get the values of all parameters of query string from URL.

Example: www.xyz.com?author=bloggingdeveloper&a1=hello

I want to get values of author and a1 parameters using JavaScript.

Styx
  • 9,863
  • 8
  • 43
  • 53
amit
  • 109
  • 1
  • 1
  • 6
  • 1
    So many duplicates to choose from in the "Related" list... – Pekka Oct 11 '11 at 07:30
  • the SO droids so busy showing off they don't understand the question... he is asking to return _ALL_ query parameters as array not a query parameter he is expecting. – Toskan Nov 02 '17 at 03:06

10 Answers10

21

The simplest way to do so is:-

const search = /*your search query ex:-?author=bloggingdeveloper&a1=hello*/
const params = new URLSearchParams(search);
let paramObj = {};
for(var value of params.keys()) {
     paramObj[value] = params.get(value);
 }

if you console paramObj you will get :-

{
author: bloggingdeveloper,
a1: hello
}

simple!!

refer:- https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/keys

Ayesha Mundu
  • 1,075
  • 2
  • 11
  • 18
  • 1
    Thanks man! You are a hero. I also added my own answer with a little bit of functional es6. =) – Dan Zuzevich Jan 16 '19 at 15:20
  • 1
    Note: You will need a polyfill for URLSearchParams in Internet Explorer. – Johnny Oshika Jan 08 '20 at 19:34
  • iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations. Any idea on this – Tushar Mistry Oct 11 '21 at 09:19
6

If you are dealing with good developers, I don't think this is overly complicated to reason about. Converts the iterator from param.keys() to an array so you can use reduce.

const params = new URLSearchParams(window.location.search);

const paramsObj = Array.from(params.keys()).reduce(
  (acc, val) => ({ ...acc, [val]: params.get(val) }),
  {}
);

This will give you an object like so:

{
  a: any,
  b: any,
  c: any,
  ...etc
}

Of course a,b,c and hypothetical query param names, as well as the "any" used.

Dan Zuzevich
  • 3,651
  • 3
  • 26
  • 39
4
function getUrlVars()
{
    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;
}

var author = getUrlVars()["author"];
var a1 = getUrlVars()["a1"];
TimT
  • 1,576
  • 16
  • 14
  • 1
    The function might be fine, the last two lines are not. You parse the query string twice - better assign the returned value to another variable. Oh, and you forgot a `=` in the last lines. – ThiefMaster Oct 11 '11 at 07:40
3

You can use something like this:

function parseQuerystring(){
    var foo = window.location.href.split('?')[1].split('#')[0].split('&');
    var dict = {};
    var elem = [];
    for (var i = foo.length - 1; i >= 0; i--) {
        elem = foo[i].split('=');
        dict[elem[0]] = elem[1];
    };
    return dict;
};

Function return JS-object from your querystring.

//www.xyz.com?author=bloggingdeveloper&a1=hello
>parseQuerystring()
{
  author: bloggingdeveloper,
  a1: hello
}
NilColor
  • 3,462
  • 3
  • 30
  • 44
2

I found this question and started using the answer suggested by TimT, but found that I would run into situations where my URL did not always have a query string. TimT's function would simply return the URL, but I found it better to either return an array of vars from the query string OR simply return false for easy checking.

I further changed it to use window.location.search, as the query string is already provided to us without having to separate it out.

function getUrlVars() {
    var vars = [], hash;
    var query_string = window.location.search;

    if (query_string) {
        var hashes = query_string.slice(1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1];
        }

        return vars;
    } else {
        return false;
    }
}
TheGremlyn
  • 323
  • 1
  • 3
  • 21
  • you are abusing your array... you are not using it https://stackoverflow.com/questions/47067229/why-does-each-not-work-with-arrays-that-have-a-string-index-in-jquery/47067269#47067269 – Toskan Nov 02 '17 at 04:08
  • you probably want to call `decodeURIComponent(hash[1]);` – Toskan Nov 02 '17 at 04:12
  • @Toskan thanks for digging this up, I guess I wasn't that good at JS 3 years ago, lol. – TheGremlyn Nov 02 '17 at 13:24
2

try this:

function urlParameter() {
    var url = window.location.href,
    retObject = {},
    parameters;

    if (url.indexOf('?') === -1) {
        return null;
    }

    url = url.split('?')[1];

    parameters = url.split('&');

    for (var i = 0; i < parameters.length; i++) {
        retObject[parameters[i].split('=')[0]] = parameters[i].split('=')[1];
    }

    return retObject;
}

output json object:

{
     author : 'bloggingdeveloper',
     a1 : 'hello'
}

get a specific value:

var author = urlParameter().author;
alert(author);
Shlomi Komemi
  • 5,445
  • 3
  • 28
  • 41
0

Set an identification on the URL like url.com?id=9, then send this as a parameter to call the function and use URLSearchParams.

Cooper Buckingham
  • 2,503
  • 2
  • 15
  • 23
0

Use that

var get_vars = window.location.search;
var patt1 = /author\=(.+)\&/;
alert(get_vars.match(patt1)[1]);

The above code acts like that

loading into get_vars variable only the query string from the domain
then assinging a regular expression pattern into patt1 that can match the author variable and it;s value
finaly alerting the matched username

KodeFor.Me
  • 13,069
  • 27
  • 98
  • 166
0
          var search = function() {
          var p = window.location.search.substr(1).split(/\&/), l = p.length, kv, r = {};
          while (l--) {
             kv = p[l].split(/\=/);
             r[kv[0]] = kv[1] || true; //if no =value just set it as true
          }
             return r;
          }();
balaphp
  • 1,306
  • 5
  • 20
  • 40
0

This stores the URL Parameters so is efficient (granted it uses a global :-( ):

var urlParams = {};
(function () {
    var e,
    a = /\+/g,  // Regex for replacing addition symbol with a space
    r = /([^&=]+)=?([^&]*)/g,
    d = function (s) {
        return decodeURIComponent(s.replace(a, " "));
    },
    q = window.location.search.substring(1);

    while (e = r.exec(q))
        urlParams[d(e[1])] = d(e[2]);
})();
Manse
  • 37,765
  • 10
  • 83
  • 108