Coder Perfect

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


I have the following URL with several GET parameters: 

I’m looking for the total value of c. I tried reading the URL, but all I got was m2. How do I accomplish this with JavaScript?

Asked by joe

Solution #1

There is no built-in support for query string arguments in JavaScript.

The URL object (which is part of the APIs supplied by browsers to JS) can be used in code running in a (modern) browser:

You can use this polyfill or the code from the original version of this answer that precedes URL: for older browsers (including Internet Explorer).

You could access, 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 may use this to parse it:

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

var query =;
var qs = parse_query_string(query);

Answered by Quentin

Solution #2

The names and values are not URL-decoded in the majority of implementations I’ve seen.

Here’s a useful utility function that also decodes URLs correctly:

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

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

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

    return params;

//var query = getQueryParams(;

Answered by Ates Goral

Solution #3


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://')

Answered by Haim Evgi

Solution #4

This is a quick technique to verify a single parameter:

Example URL:


Example Javascript:

var myParam ='myParam=')[1]

If the URL contains the word “myParam,” the variable myParam will be set to “2,” otherwise it will be undefined.

In that instance, perhaps you’d like a default value:

var myParam ='myParam=')[1] ?'myParam=')[1] : 'myDefaultValue';

Update: This is more effective:

var url = ""; // or window.location.href for current url
var captured = /myParam=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
var result = captured ? captured : 'myDefaultValue';

It also works when the URL contains a lot of parameters.

Answered by mzalazar

Solution #5

The URL and URLSearchParams APIs have been introduced by browser vendors as a native way to achieve this.

let url = new URL('');
let searchParams = new URLSearchParams(;
console.log(searchParams.get('c'));  // outputs "m2-m3-m4-m5"

Firefox, Opera, Safari, Chrome, and Edge are currently supported. Here’s a list of browsers that support it.

For browsers that aren’t supported, Google developer Eric Bidelman recommends using this polyfill.

Answered by cgatian

Post is based on