2694

Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how? If not, is there a plugin which can do so?

6
  • I use the plugin getUrlParam described in jQuery-Plugin – getUrlParam (version 2).
    – coma
    Commented May 23, 2009 at 8:19
  • 69
    A plain javascript solution without RegEx: css-tricks.com/snippets/javascript/get-url-variables Commented Oct 29, 2012 at 14:50
  • 6
    Although the top solution to the question deserves its popularity because of its excellent observation that jQuery is not needed, its method of creating new regular expressions and re-parsing the query string for every parameter desired is extremely inefficient. Far more efficient (and versatile) solutions have been in existence for a long time, for example within this article reprinted here: htmlgoodies.com/beyond/javascript/article.php/11877_3755006_3/… Commented May 14, 2013 at 6:00
  • 1
    possible duplicate of JavaScript query string
    – user456814
    Commented Jul 31, 2013 at 23:09
  • 4
    Joseph, the "excellent observation that jQuery is not needed"? Of course it's not needed. Everything jQuery does, it does using JavaScript. People don't use jQuery because it does stuff that JavaScript can't do. The point of jQuery is convenience.
    – Val Kornea
    Commented May 30, 2014 at 1:12

73 Answers 73

26

See it in Action: https://codepen.io/ajorpheus/pen/XWyWWNQ


http://someurl.com?key=value&keynovalue&keyemptyvalue=&&keynovalue=nowhasvalue#somehash
  • Regular key/value pair (?param=value)
  • Keys w/o value (?param : no equal sign or value)
  • Keys w/ empty value (?param= : equal sign, but no value to right of equal sign)
  • Repeated Keys (?param=1&param=2)
  • Removes Empty Keys (?&& : no key or value)

###Code:

-

    var queryString = window.location.search || '';
    var keyValPairs = [];
    var params      = {};
    queryString     = queryString.substr(1);

    if (queryString.length)
    {
       keyValPairs = queryString.split('&');
       for (pairNum in keyValPairs)
       {
          var key = keyValPairs[pairNum].split('=')[0];
          if (!key.length) continue;
          if (typeof params[key] === 'undefined')
             params[key] = [];
          params[key].push(keyValPairs[pairNum].split('=')[1]);
       }
    }

###How to Call:

-

    params['key'];  // returns an array of values (1..n)

###Output:

-

    key            ["value"]
    keyemptyvalue  [""]
    keynovalue     [undefined, "nowhasvalue"]
23

This one works fine. Regular expressions in some of the other answers introduce unnecessary overhead.

function getQuerystring(key) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == key) {
            return pair[1];
        }
    }
}

taken from here

3
  • 3
    You probably at least want to call decodeUriComponent on the pair[1] before you return it, if not replace pluses with spaces first as in all the other solutions here. Some of the other solutions also prefer a limit of 2 parts on the split = to be more lenient in accepting input.
    – Rup
    Commented May 24, 2012 at 8:44
  • 1
    @Rup you are right...actually in my code it'll always be a number rather than any special characters, so missed ...
    – IT ppl
    Commented May 24, 2012 at 9:22
  • Thanks for it! It's the only method supported by the Kindle's Experimental Browser. Freak project here! :·) Commented Nov 25, 2019 at 1:51
21

I developed a small library using techniques listed here to create an easy to use, drop-in solution to anyones troubles; It can be found here:

https://github.com/Nijikokun/query-js

Usage

Fetching specific parameter/key:

query.get('param');

Using the builder to fetch the entire object:

var storage = query.build();
console.log(storage.param);

and tons more... check the github link for more examples.

Features

  1. Caching on both decoding and parameters
  2. Supports hash query strings #hello?page=3
  3. Supports passing custom queries
  4. Supports Array / Object Parameters user[]="jim"&user[]="bob"
  5. Supports empty management &&
  6. Supports declaration parameters without values name&hello="world"
  7. Supports repeated parameters param=1&param=2
  8. Clean, compact, and readable source 4kb
  9. AMD, Require, Node support
20

One-liner to get the query:

var value = location.search.match(new RegExp(key + "=(.*?)($|\&)", "i"))[1];
4
  • 6
    Triggers error if the key doesn't exist, try this maybe? (location.search.match(new RegExp('kiosk_modeasdf' + "=(.*?)($|\&)", "i")) || [])[1]
    – Brad Koch
    Commented Jan 28, 2013 at 20:51
  • @Brad, of course it's undefined, since that's the key you're looking for. if your query is?hello=world, var value = location.search.match(new RegExp("hello" + "=(.*?)($|\&)", "i"))[1]; will return "world"
    – tim
    Commented Feb 13, 2013 at 1:38
  • 2
    @BradKoch I found your solution this best, especially with a short circuit to an empty string (window.location.search.match(new RegExp('kiosk_modeasdf' + "=(.*?)($|\&)", "i")) || [])[1] || '';
    – rob
    Commented Sep 30, 2014 at 7:41
  • i think you forgot testing for key starting with either '?' or '&' like: var result = location.search.match(new RegExp("[\?\&]" + key + "=(.*?)($|\&)", "i"));
    – e-frank
    Commented Oct 10, 2017 at 14:45
18

Here is my version of query string parsing code on GitHub.

It's "prefixed" with jquery.*, but the parsing function itself don't use jQuery. It's pretty fast, but still open for few simple performance optimizations.

Also it supports list & hash-tables encoding in the URL, like:

arr[]=10&arr[]=20&arr[]=100

or

hash[key1]=hello&hash[key2]=moto&a=How%20are%20you

jQuery.toQueryParams = function(str, separator) {
    separator = separator || '&'
    var obj = {}
    if (str.length == 0)
        return obj
    var c = str.substr(0,1)
    var s = c=='?' || c=='#'  ? str.substr(1) : str; 

    var a = s.split(separator)
    for (var i=0; i<a.length; i++) {
        var p = a[i].indexOf('=')
        if (p < 0) {
            obj[a[i]] = ''
            continue
        }
        var k = decodeURIComponent(a[i].substr(0,p)),
            v = decodeURIComponent(a[i].substr(p+1))

        var bps = k.indexOf('[')
        if (bps < 0) {
            obj[k] = v
            continue;
        } 

        var bpe = k.substr(bps+1).indexOf(']')
        if (bpe < 0) {
            obj[k] = v
            continue;
        }

        var bpv = k.substr(bps+1, bps+bpe-1)
        var k = k.substr(0,bps)
        if (bpv.length <= 0) {
            if (typeof(obj[k]) != 'object') obj[k] = []
            obj[k].push(v)
        } else {
            if (typeof(obj[k]) != 'object') obj[k] = {}
            obj[k][bpv] = v
        }
    }
    return obj;

}
2
  • nice but doesnt deal with the case filters[topic][]=list
    – brauliobo
    Commented Sep 19, 2019 at 18:11
  • Hey, how to use the above code to get value by Key?? I want to get city values from this URL... abc.xyzl/urlpart1/… Commented Dec 23, 2020 at 11:46
18

A very lightweight jQuery method:

var qs = window.location.search.replace('?','').split('&'),
    request = {};
$.each(qs, function(i,v) {
    var initial, pair = v.split('=');
    if(initial = request[pair[0]]){
        if(!$.isArray(initial)) {
            request[pair[0]] = [initial]
        }
        request[pair[0]].push(pair[1]);
    } else {
        request[pair[0]] = pair[1];
    }
    return;
});
console.log(request);

And to alert, for example ?q

alert(request.q)
2
  • 2
    Neat. There's a few answers in the same vein already - iterating over a split - albeit none using jQuery's each, and I don't think any of them are perfect yet either. I don't understand the return in your closure though, and I think you need to decodeUriComponent the two pair[] values as you read them.
    – Rup
    Commented Apr 2, 2013 at 8:48
  • yea having the decodeUriComponent is def best practice- i just kinda wrote that on the fly. As for the return... i just stay in the habit of returning something. totally not necessary
    – Roi
    Commented May 13, 2013 at 20:55
18

I would rather use split() instead of Regex for this operation:

function getUrlParams() {
    var result = {};
    var params = (window.location.search.split('?')[1] || '').split('&');
    for(var param in params) {
        if (params.hasOwnProperty(param)) {
            var paramParts = params[param].split('=');
            result[paramParts[0]] = decodeURIComponent(paramParts[1] || "");
        }
    }
    return result;
}
1
  • I wasn't wanting to use Regex and went with this solution. I find it works rather nicely. Thanks!
    – dogonaroof
    Commented Feb 8, 2019 at 11:51
13

Here's what I'm using:

/**
 * Examples:
 * getUrlParams()['myparam']    // url defaults to the current page
 * getUrlParams(url)['myparam'] // url can be just a query string
 *
 * Results of calling `getUrlParams(url)['myparam']` with various urls:
 * example.com                               (undefined)
 * example.com?                              (undefined)
 * example.com?myparam                       (empty string)
 * example.com?myparam=                      (empty string)
 * example.com?myparam=0                     (the string '0')
 * example.com?myparam=0&myparam=override    (the string 'override')
 *
 * Origin: http://stackoverflow.com/a/23946023/2407309
 */
function getUrlParams (url) {
    var urlParams = {} // return value
    var queryString = getQueryString()
    if (queryString) {
        var keyValuePairs = queryString.split('&')
        for (var i = 0; i < keyValuePairs.length; i++) {
            var keyValuePair = keyValuePairs[i].split('=')
            var paramName = keyValuePair[0]
            var paramValue = keyValuePair[1] || ''
            urlParams[paramName] = decodeURIComponent(paramValue.replace(/\+/g, ' '))
        }
    }
    return urlParams // functions below
    function getQueryString () {
        var reducedUrl = url || window.location.search
        reducedUrl = reducedUrl.split('#')[0] // Discard fragment identifier.
        var queryString = reducedUrl.split('?')[1]
        if (!queryString) {
            if (reducedUrl.search('=') !== false) { // URL is a query string.
                queryString = reducedUrl
            }
        }
        return queryString
    } // getQueryString
} // getUrlParams

Returning 'override' rather than '0' in the last case makes it consistent with PHP. Works in IE7.

5
  • 1
    That's because everyone seems to have different requirements for handling keys without values or handling duplicated keys by building arrays of values, etc. There are plenty of split answers already but I don't see one that does exactly the same as this one, true. (FWIW I think paramName needs to be decodeURIComponented too technically, though I doubt anyone would use non-trivial params.)
    – Rup
    Commented Jun 2, 2014 at 7:22
  • 1
    Parameter names should never need decoding.
    – Val Kornea
    Commented Nov 18, 2014 at 11:43
  • 2
    Why not? HTML 5 doesn't restrict the character set for input control names, nor is there any guarantee that they come from HTML anyway. I can't see why there would be a restriction to printable characters.
    – Rup
    Commented Nov 18, 2014 at 12:09
  • 1
    The solution is good, but why no semicolon at the end of statements?
    – Sudar
    Commented Apr 1, 2015 at 7:19
  • 2
    @Sudar Because there is no reason to have them. Most people always include them just because they've always seen other people include them and because other languages require them; often they are wrongly regarded as required in JavaScript as well, which sometimes causes baffling problems. Doing things for no reason is generally misleading; JavaScript is not C++ or PHP. Look up defensive semicolon.
    – Val Kornea
    Commented Apr 1, 2015 at 12:04
11

For those who wants a short method (with limitations):

location.search.split('myParameter=')[1]
3
  • 4
    That's not enough for the general case: it assumes 1) that you're only interested in a single parameter 2) that it's guaranteed to be the last parameter in the line (i.e. you can guarantee that all browsers will put it last, or it's the only param on the page, and that you're not going to e.g. put the URL in an RSS feed aggregator where it might get utm parameters added) and 3) that there are no characters in the value that can be escaped for transmission, e.g. spaces or many symbols.
    – Rup
    Commented Apr 14, 2014 at 10:21
  • 2
    There's no 1 size fits all methods. If you have a perfect solution in a one-short-liner, I'll be all eyes and ears to check that out. Above is a quick solution, not for general case, but for coders who want a light weight and quick solution to static implementations. In any case, thanks for your comment.
    – George
    Commented Apr 14, 2014 at 14:40
  • 2
    (location.search.split('myParameter=')[1]).split('&')[0] ; this gives you the same result in case of multiple parameters. Still useful only for static implementations.
    – Anurag
    Commented Aug 1, 2014 at 7:05
10

Get all querystring parameters including checkbox values (arrays).

Considering the correct & normal use of GET parameters, the things I see it's missing, on most functions, is the support for arrays and removing the hash data.

So I wrote this function:

function qs(a){
 if(!a)return {};
 a=a.split('#')[0].split('&');
 var b=a.length,c={},d,k,v;
 while(b--){
  d=a[b].split('=');
  k=d[0].replace('[]',''),v=decodeURIComponent(d[1]||'');
  c[k]?typeof c[k]==='string'?(c[k]=[v,c[k]]):(c[k].unshift(v)):c[k]=v;
 }
 return c
}

Using shorthand operators & while-- loop, the performance should be very good to.

Support:

  1. Empty values (key= / key)
  2. Key value (key=value)
  3. Arrays (key[]=value)
  4. Hash (the hash tag is split out)

Notes:

It does not support object arrays (key[key]=value)

If the space is + it remains a +.

Add .replace(/\+/g, " ") if you need.

Usage:

qs('array[]=1&array[]=2&key=value&empty=&empty2#hash')

Return:

{
    "empty": "",
    "key": "value",
    "array": [
        "1",
        "2"
    ]
}

Demo:

http://jsfiddle.net/ZQMrt/1/

Info

If you don't understand something or you can't read the function just ask. I'm happy to explain what I did here.

If you think the function is unreadable and unmaintainable I'm happy to rewrite the function for you, but consider that shorthand & bitwise operators are always faster than a standard syntax (maybe read about shorthands and bitwise operators in the ECMA-262 book or use your favorite search engine). Rewriting the code in a standard readable syntax means performance loss.

3
  • Very neat, though I find it hard to believe that writing it pre-minified actually helps anything but the first parse, or helps in general if people are going to minify their production code anyway. Most of the functions here don't need to strip the hash-part because they start with location.search which doesn't contain it. I'm also not clear what you mean "bitwise operators" - you're using empty-or-undefined-is-false in a couple of places which is as close as you get but there's no bit manipulation here.
    – Rup
    Commented Jan 26, 2014 at 18:55
  • If you use arrays for more than checkbox values, add: if ( v.charAt(0) == '[' ) { v = v.replace('[', '["').replace(']', '"]').replace(',', '","'); v = JSON && JSON.parse(v) || $.parseJSON(v); } before "c[k]?typeof ..."
    – Alex
    Commented Jul 27, 2015 at 12:40
  • I need one that supports object arrays
    – brauliobo
    Commented Sep 19, 2019 at 18:16
9
function getUrlVar(key){
    var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search); 
    return result && unescape(result[1]) || ""; 
}

https://gist.github.com/1771618

8

The following code will create an object which has two methods:

  1. isKeyExist: Check if a particular parameter exist
  2. getValue: Get the value of a particular parameter.

 

var QSParam = new function() {
       var qsParm = {};
       var query = window.location.search.substring(1);
       var params = query.split('&');
       for (var i = 0; i < params.length; i++) {
           var pos = params[i].indexOf('=');
           if (pos > 0) {
               var key = params[i].substring(0, pos);
               var val = params[i].substring(pos + 1);
               qsParm[key] = val;
           }
       }
       this.isKeyExist = function(query){
           if(qsParm[query]){
               return true;
           }
           else{
              return false;
           }
       };
       this.getValue = function(query){
           if(qsParm[query])
           {
               return qsParm[query];
           }
           throw "URL does not contain query "+ query;
       }
};
8

Try this:

String.prototype.getValueByKey = function(k){
    var p = new RegExp('\\b'+k+'\\b','gi');
    return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p)+k.length+1).substr(0,this.substr(this.search(p)+k.length+1).search(/(&|;|$)/))) : "";
};

Then call it like so:

if(location.search != "") location.search.getValueByKey("id");

You can use this for cookies also:

if(navigator.cookieEnabled) document.cookie.getValueByKey("username");

This only works for strings that have key=value[&|;|$]... will not work on objects/arrays.

If you don't want to use String.prototype... move it to a function and pass the string as an argument

7

Here's my own take on this. This first function decodes a URL string into an object of name/value pairs:

url_args_decode = function (url) {
  var args_enc, el, i, nameval, ret;
  ret = {};
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  // strip off initial ? on search and split
  args_enc = el.search.substring(1).split('&');
  for (i = 0; i < args_enc.length; i++) {
    // convert + into space, split on =, and then decode 
    args_enc[i].replace(/\+/g, ' ');
    nameval = args_enc[i].split('=', 2);
    ret[decodeURIComponent(nameval[0])]=decodeURIComponent(nameval[1]);
  }
  return ret;
};

And as an added bonus, if you change some of the args, you can use this second function to put the array of args back into the URL string:

url_args_replace = function (url, args) {
  var args_enc, el, name;
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  args_enc = [];
  // encode args to go into url
  for (name in args) {
    if (args.hasOwnProperty(name)) {
      name = encodeURIComponent(name);
      args[name] = encodeURIComponent(args[name]);
      args_enc.push(name + '=' + args[name]);
    }
  }
  if (args_enc.length > 0) {
    el.search = '?' + args_enc.join('&');
  } else {
    el.search = '';
  }
  return el.href;
};
3
  • 1
    If your anyway using the jQuery, Then the later method (url_args_replace) can be used via $.param()
    – adardesign
    Commented Aug 28, 2012 at 13:51
  • 1
    Why do you use document.createElement("a") ?
    – greg
    Commented Apr 18, 2013 at 2:10
  • 2
    @greg to create the element in the browser engine, which will parse a url for you and provide search and href methods for interacting with the url string.
    – BMitch
    Commented Apr 18, 2013 at 2:15
7

I used this code (JavaScript) to get the what is passed through the URL:

function getUrlVars() {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                vars[key] = value;
            });
            return vars;
        }

Then to assign the value to a variable, you only have to specify which parameter you want to get, ie if the URL is example.com/?I=1&p=2&f=3

You can do this to get the values:

var getI = getUrlVars()["I"];
var getP = getUrlVars()["p"];
var getF = getUrlVars()["f"];

then the values would be:

getI = 1, getP = 2 and getF = 3
2
  • 1
    That's neat, although it's missing decodeURIComponent on the key and the value and you probably don't need the i flag on the regexp (not that that really matters).
    – Rup
    Commented Sep 8, 2013 at 22:40
  • 1
    but what if you have example.com/3 (MVC routing) Commented Jun 7, 2017 at 19:02
6

The following function returns an object version of your queryString. You can simply write obj.key1 and obj.key2 to access values of key1 and key2 in parameter.

function getQueryStringObject()
{
    var querystring = document.location.search.replace('?','').split( '&' );
    var objQueryString={};
    var key="",val="";
    if(typeof querystring == 'undefined')
    {
        return (typeof querystring);
    }
    for(i=0;i<querystring.length;i++)
    {
        key=querystring[i].split("=")[0];
        val=querystring[i].split("=")[1];
        objQueryString[key] = val;
    }
    return objQueryString;
}

And to use this function you can write

var obj= getQueryStringObject();
alert(obj.key1);
6

This function converts the querystring to a JSON-like object, it also handles value-less and multi-value parameters:

"use strict";
function getQuerystringData(name) {
    var data = { };
    var parameters = window.location.search.substring(1).split("&");
    for (var i = 0, j = parameters.length; i < j; i++) {
        var parameter = parameters[i].split("=");
        var parameterName = decodeURIComponent(parameter[0]);
        var parameterValue = typeof parameter[1] === "undefined" ? parameter[1] : decodeURIComponent(parameter[1]);
        var dataType = typeof data[parameterName];
        if (dataType === "undefined") {
            data[parameterName] = parameterValue;
        } else if (dataType === "array") {
            data[parameterName].push(parameterValue);
        } else {
            data[parameterName] = [data[parameterName]];
            data[parameterName].push(parameterValue);
        }
    }
    return typeof name === "string" ? data[name] : data;
}

We perform a check for undefined on parameter[1] because decodeURIComponent returns the string "undefined" if the variable is undefined, and that's wrong.

Usage:

"use strict";
var data = getQuerystringData();
var parameterValue = getQuerystringData("parameterName");
6

I did a small URL library for my needs here: https://github.com/Mikhus/jsurl

It's a more common way of manipulating the URLs in JavaScript. Meanwhile it's really lightweight (minified and gzipped < 1 KB) and has a very simple and clean API. And it does not need any other library to work.

Regarding the initial question, it's very simple to do:

var u = new Url; // Current document URL
// or
var u = new Url('http://user:[email protected]:8080/some/path?foo=bar&bar=baz#anchor');

// Looking for query string parameters
alert( u.query.bar);
alert( u.query.foo);

// Modifying query string parameters
u.query.foo = 'bla';
u.query.woo = ['hi', 'hey']

alert(u.query.foo);
alert(u.query.woo);
alert(u);
3
  • That's interesting. Why decode the value manually? You'll also limited in the top character code you can accept as UTF-8, although I realise you're unlikely to ever hit that in practice.
    – Rup
    Commented Apr 19, 2013 at 9:00
  • Why decoding in that way explained here: unixpapa.com/js/querystring.html Actually, I've took the code for that idea from there, what is stated in a top-level comment at my script
    – Mikhus
    Commented Apr 19, 2013 at 9:28
  • also doesnt't support object arrays like filters[topic][]=list
    – brauliobo
    Commented Sep 19, 2019 at 18:19
5

I took this answer and added support for optionally passing the URL in as a parameter; falls back to window.location.search. Obviously this is useful for getting the query string parameters from URLs that are not the current page:

(function($, undef) {
  $.QueryString = function(url) {
    var pairs, qs = null, index, map = {};
    if(url == undef){
      qs = window.location.search.substr(1);
    }else{
      index = url.indexOf('?');
      if(index == -1) return {};
      qs = url.substring(index+1);
    }
    pairs = qs.split('&');
    if (pairs == "") return {};
    for (var i = 0; i < pairs.length; ++i)
    {
      var p = pairs[i].split('=');
      if(p.length != 2) continue;
      map[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return map;
  };
})(jQuery);
5

If you have Underscore.js or lodash, a quick and dirty way to get this done is:

_.object(window.location.search.slice(1).split('&').map(function (val) { return val.split('='); }));
3
  • Neat. Compared to the top split-based answer though you're missing handling of +s and the decodeURIComponent calls, but for simple values this will be enough.
    – Rup
    Commented Nov 20, 2013 at 15:32
  • Yeah, it's really just meant for grabbing simple alphanumeric tokens. In a current project, it's all I needed, so I didn't really want a hulking function.
    – acjay
    Commented Nov 21, 2013 at 6:18
  • 1
    this is what I use to make a key value object of the query parameters: _.chain(document.location.search.slice(1).split('&')).invoke('split', '=').object().value() Commented Jan 7, 2014 at 14:46
4

There is a nice little url utility for this with some cool sugaring:

http://www.example.com/path/index.html?silly=willy#chucky=cheese

url();            // http://www.example.com/path/index.html?silly=willy#chucky=cheese
url('domain');    // example.com
url('1');         // path
url('-1');        // index.html
url('?');         // silly=willy
url('?silly');    // willy
url('?poo');      // (an empty string)
url('#');         // chucky=cheese
url('#chucky');   // cheese
url('#poo');      // (an empty string)

Check out more examples and download here: https://github.com/websanova/js-url#url

4

This the most simple and small function JavaScript to get int ans String parameter value from URL

/* THIS FUNCTION IS TO FETCH INT PARAMETER VALUES */

function getParameterint(param) {
            var val = document.URL;
            var url = val.substr(val.indexOf(param))  
            var n=parseInt(url.replace(param+"=",""));
            alert(n); 
}
getParameteraint("page");
getParameteraint("pagee");

/*THIS FUNCTION IS TO FETCH STRING PARAMETER*/
function getParameterstr(param) {
            var val = document.URL;
            var url = val.substr(val.indexOf(param))  
            var n=url.replace(param+"=","");
            alert(n); 
}
getParameterstr("str");

Source And DEMO : http://bloggerplugnplay.blogspot.in/2012/08/how-to-get-url-parameter-in-javascript.html

3
  • 2
    I think that can be easily defeated e.g. ?xyz=page&str=Expected&page=123 won't return 123 because it picks up the page string from xyz=page, and str will return Expected&page=123 rather than just Expected if it's not the last value on the line, etc. You're also not decodeUriComponent-ing the values extracted. Plus I couldn't try your demo - I got redirected to a betting website??
    – Rup
    Commented Jan 25, 2013 at 12:23
  • @Rup you are talking about a RARE/WORST case.. But in normal and regular cases this code works fine and solves the purpose ...And about DEMO its working fine and shows how this function works! Thanks !
    – Code Spy
    Commented Jan 29, 2013 at 5:20
  • 2
    OK, finally managed to get your demo through adfly. Yes, that works OK but only because you have just the one string parameter and it's last - try using more than one and switching the orders around. Try putting the pagee parameter before the page parameter and it'll fail. For example here's your demo with the order of the three reversed. The other problem is if someone posts a string with a non-ASCII character in it, e.g. a space - it'll get URI encoded and you're not decoding that afterwards.
    – Rup
    Commented Jan 29, 2013 at 11:49
4

I believe this to be an accurate and concise way to achieve this (modified from http://css-tricks.com/snippets/javascript/get-url-variables/):

function getQueryVariable(variable) {

    var query = window.location.search.substring(1),            // Remove the ? from the query string.
        vars = query.split("&");                                // Split all values by ampersand.

    for (var i = 0; i < vars.length; i++) {                     // Loop through them...
        var pair = vars[i].split("=");                          // Split the name from the value.
        if (pair[0] == variable) {                              // Once the requested value is found...
            return ( pair[1] == undefined ) ? null : pair[1];   // Return null if there is no value (no equals sign), otherwise return the value.
        }
    }

    return undefined;                                           // Wasn't found.

}
1
  • 1
    That looks reasonable! You probably need to decode the values taken from the query string in case they've been encoded for submission with %s or +s though.
    – Rup
    Commented Mar 17, 2013 at 12:31
4

There's a robust implementation in Node.js's source
https://github.com/joyent/node/blob/master/lib/querystring.js

Also TJ's qs does nested params parsing
https://github.com/visionmedia/node-querystring

4
var getUrlParameters = function (name, url) {
    if (!name) {
        return undefined;
    }

    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    url = url || location.search;

    var regex = new RegExp('[\\?&#]' + name + '=?([^&#]*)', 'gi'), result, resultList = [];

    while (result = regex.exec(url)) {
        resultList.push(decodeURIComponent(result[1].replace(/\+/g, ' ')));
    }

    return resultList.length ? resultList.length === 1 ? resultList[0] : resultList : undefined;
};
1
  • 1
    this is a lot better than accepted solution to handle array values in query string. i.e. arr[]=1&arr[]=2
    – allenhwkim
    Commented Aug 24, 2013 at 20:40
4

There are many solutions to retrieve URI query values, I prefer this one because it's short and works great:

function get(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}
1
  • That's neat, although that's essentially the top accepted answer distilled down a bit, e.g. you've lost the decoding of pluses-for-spaces in values . The encodeURIComponent for the key name is new, though, and on one hand more correct than the accepted answer for considering encodings in the key but on the other will still miss non-minimal encodings, e.g. get("key") won't match ?k%65y=value.
    – Rup
    Commented Sep 8, 2013 at 22:37
4

A simple solution with plain JavaScript and regular expressions:

alert(getQueryString("p2"));

function getQueryString (Param) {
    return decodeURI("http://www.example.com/?p1=p11&p2=p2222".replace(new RegExp("^(?:.*[&?]" + encodeURI(Param).replace(/[.+*]/g, "$&") + "(?:=([^&]*))?)?.*$", "i"), "$1"));
}

JsFiddle

4

If you want array-style parameters URL.js supports arbitrarily nested array-style parameters as well as string indexes (maps). It also handles URL decoding.

url.get("val[0]=zero&val[1]=one&val[2]&val[3]=&val[4]=four&val[5][0]=n1&val[5][1]=n2&val[5][2]=n3&key=val", {array:true});
// Result
{
    val: [
        'zero',
        'one',
        true,
        '',
        'four',
        [ 'n1', 'n2', 'n3' ]
    ]
    key: 'val'
}
4

If you do not wish to use a JavaScript library you can use the JavaScript string functions to parse window.location. Keep this code in an external .js file and you can use it over and over again in different projects.

// Example - window.location = "index.htm?name=bob";

var value = getParameterValue("name");

alert("name = " + value);

function getParameterValue(param)
{
    var url = window.location;
    var parts = url.split('?');
    var params = parts[1].split('&');
    var val = "";

    for ( var i=0; i<params.length; i++)
    {
        var paramNameVal = params[i].split('=');

        if ( paramNameVal[0] == param )
        {
            val = paramNameVal[1];
        }
    }
    return val;
}
4

This is very simple method to get parameter value(query string)

Use gV(para_name) function to retrieve its value

var a=window.location.search;
a=a.replace(a.charAt(0),""); //Removes '?'
a=a.split("&");

function gV(x){
 for(i=0;i<a.length;i++){
  var b=a[i].substr(0,a[i].indexOf("="));
  if(x==b){
   return a[i].substr(a[i].indexOf("=")+1,a[i].length)}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.