Categories
javascript url url-parameters

Get the values from the “GET” parameters (JavaScript) [duplicate]

1652

I have a URL with some GET parameters as follows:

www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 

I need to get the whole value of c. I tried to read the URL, but I got only m2. How do I do this using JavaScript?

3

  • 8

    Before you post a new answer, consider there are already 50+ answers for this question. Please, make sure that your answer contributes information that is not among existing answers.

    – janniks

    Feb 3, 2020 at 12:04

  • var url_string = “example.com/t.html?a=1&b=3&c=m2-m3-m4-m5“; //window.location.href var url = new URL(url_string); var c = url.searchParams.get(“c”); console.log(c);

    Aug 3, 2021 at 16:56

  • 1

    It is insane that a, what is should be, simple question for JS requires 50+ answers :/

    – fguillen

    Sep 28, 2021 at 11:45

2565

JavaScript itself has nothing built in for handling query string parameters.

Code running in a (modern) browser can use the URL object (which is part of the APIs provided by browsers to JS):

var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);

For older browsers (including Internet Explorer), you can use this polyfill.


You could also use the code from the original version of this answer that predates URL. The above polyfill is robust and well tested and I strongly recommend it over this though.

You could access location.search, which would give you from the ? character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.

Then you can parse it with this:

function parse_query_string(query) {
  var vars = query.split("&");
  var query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    var key = decodeURIComponent(pair.shift());
    var value = decodeURIComponent(pair.join("="));
    // If first entry with this name
    if (typeof query_string[key] === "undefined") {
      query_string[key] = value;
      // If second entry with this name
    } else if (typeof query_string[key] === "string") {
      var arr = [query_string[key], value];
      query_string[key] = arr;
      // If third or later entry with this name
    } else {
      query_string[key].push(value);
    }
  }
  return query_string;
}

var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);

You can get the query string from the URL of the current page with:

var query = window.location.search.substring(1);
var qs = parse_query_string(query);

7

  • For older browsers, you may need a polyfill for URL in addition to the one for URLSearchParams. Or you can dodge this issue by replacing the line var c = url.searchParams.get("c"); in the answer above with var c = new URLSearchParams(window.location.search).get("c");.

    Sep 24, 2018 at 0:09

  • 13

    @Jamland — Absolutely do not do that. It will break things. Here is a live demo new URL() expects to receive a properly encoded URL as its argument. decodeURIComponent expects to be passed a component of a URL, not a whole URL.

    – Quentin

    Dec 6, 2018 at 14:09


  • @Quentin I have checked different special chars and I see you are right. decodeURIComponent shouldn’t be used in this case

    – jamland

    Dec 6, 2018 at 15:42

  • the first solution can’t be used in situation when your url is like :”localhost:”

    Mar 10 at 1:19

  • @Snowmanzzz — localhost: is not a valid URL. http://localhost/path?query=something would be. http://localhost:80/path?query=something would be. The URL object handles them just fine.

    – Quentin

    Mar 10 at 8:48

259

Most implementations I’ve seen miss out URL-decoding the names and the values.

Here’s a general utility function that also does proper URL-decoding:

function getQueryParams(qs) {
    qs = qs.split('+').join(' ');

    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }

    return params;
}

//var query = getQueryParams(document.location.search);
//alert(query.foo);

11

  • 4

    This code doesn’t work. It creates an infinite loop because the regex is compiled in the loop definition which resets the current index. It works properly if you put the regex into a variable outside of the loop.

    Jul 6, 2011 at 1:22

  • 4

    @maxhawkins: It works in some browsers while it would go into an infinite loop in others. You’re half-right in that regard. I will fix the code to be cross-browser. Thanks for pointing that out!

    Jul 6, 2011 at 5:31

  • 4

    @ZiTAL This function is to be used with the query part of a URL, not the entire URL. See the commented-out usage example below.

    Feb 17, 2012 at 16:57

  • 2

    @Harvey Case insensitivity is not a concern of query parameters. It sounds like an application-specific thing that should be applied along with, or on top of query parameter extraction.

    May 26, 2016 at 21:46

  • 8

    Why qs.split('+').join(' '); and not qs.replace(/\+/g, ' '); ?

    Feb 6, 2018 at 6:58

255

source

function gup( name, url ) {
    if (!url) url = location.href;
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( url );
    return results == null ? null : results[1];
}
gup('q', 'hxxp://example.com/?q=abc')

7

  • 9

    I like this option best, but prefer to return null, or the result, but not an empty string.

    Nov 5, 2010 at 2:53

  • 2

    It looks like you have some extra escape chars. “\\[” should be “\[“. Since those are regular strings, the [ and ] don’t need to be escaped.

    – EricP

    Oct 29, 2013 at 18:24

  • This is not case insensitive. Where would I add the “i” to make it case insensitive?

    – zeta

    Jan 20, 2016 at 1:43

  • alert(gup(‘UserID’, window.location.href));

    Mar 10, 2016 at 10:35

  • if there is no parameters in the URL, results will be Null and generate an error. testing for null before attempting to parse the array could be better

    – Antony P.

    Dec 3, 2016 at 1:33