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.

2
  • 1
    So many duplicates to choose from in the "Related" list... Commented Oct 11, 2011 at 7: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. Commented Nov 2, 2017 at 3:06

10 Answers 10

24

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks man! You are a hero. I also added my own answer with a little bit of functional es6. =)
Note: You will need a polyfill for URLSearchParams in Internet Explorer.
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
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.

Comments

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"];

1 Comment

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.
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
}

Comments

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);

Comments

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;
    }
}

3 Comments

you are abusing your array... you are not using it stackoverflow.com/questions/47067229/…
you probably want to call decodeURIComponent(hash[1]);
@Toskan thanks for digging this up, I guess I wasn't that good at JS 3 years ago, lol.
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

Comments

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;
          }();

Comments

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]);
})();

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.