304

I'm looking for a jQuery plugin that can get URL parameters, and support this search string without outputting the JavaScript error: "malformed URI sequence". If there isn't a jQuery plugin that supports this, I need to know how to modify it to support this.

?search=%E6%F8%E5

The value of the URL parameter, when decoded, should be:

æøå

(the characters are Norwegian).

I don't have access to the server, so I can't modify anything on it.

Sindre Sorhus
  • 62,972
  • 39
  • 168
  • 232
  • 9
    take a look at http://stackoverflow.com/questions/901115/get-querystring-with-jquery/901144#901144 – Artem Barger Sep 10 '09 at 07:49
  • 1
    The reason that you are getting "malformed URI sequence" is because the majority of functions use `decodeURIComponent()`. The Norwegian characters were most likely encoded using something like `escape()` and changing the `decodeURIComponent()` call to an `unescape()` should help. – Kevin M Oct 23 '13 at 18:18
  • See my answer for a modern solution: http://stackoverflow.com/a/19992436/64949 – Sindre Sorhus Nov 15 '13 at 02:30

19 Answers19

418
function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}
James
  • 109,676
  • 31
  • 162
  • 175
  • 33
    With `name = 'bar'`, I think this regexp would match `'foobar=10'` and return `'10'`. Maybe you could add `'[?|&]'` at the beginning of your regexp. Cheers! – Sébastien RoccaSerra Apr 27 '11 at 10:07
  • 34
    this function returns 'null' instead of null when the parameter is not defined... the joy of js... – Damien Dec 21 '11 at 15:18
  • 12
    you may want "decodeURIComponent()" instead of "decodeURI()", especially if you are passing interesting data like return URLs in as a URL parameter – perfectionist Feb 27 '12 at 13:14
  • 25
    This is good, but decodeURIComponent is better, for example I had a hashtag (%23) in my param that would be ignored by decodeURI. And I would not return null, but "", because decodeURI(null) === "null", which is a weird return value, "" is better; you can do if (!getURLParameter("param")) instead of if (getURLParameter("param") === "null"). So, my improved version: decodeURIComponent( (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,""])[1] ) – standup75 Jun 07 '12 at 16:39
  • 2
    **This fixes 'null' instead of null issue:** function getURLParameter(name) { var param = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]; return (param?:decodeURI(param):param); } } – Sanjeev Kumar Dangi Aug 31 '12 at 11:59
  • 3
    Down voted as this returns string no matter if the result was found or not, and no matter what you put as alternative array e.g.[,null], because thre result was wrapped within decodeURI which turned anything into string, Sanjeev was right but his code wasnt tested correctly and simple copy and paste doesnt work. `function getURLParameter(name) { var p = RegExp(name + '=' + '(.+?)(&|$)').exec(location.search); if(!!p) { p = decodeURI(p[1]); } return p; }` – Lukasz 'Severiaan' Grela Feb 28 '13 at 07:56
  • This does'nt seem to work with URL : 'http://localhost:8888/?version=fghdfghd' , this accepted answer does : http://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter/979995#979995 – blue-sky May 18 '13 at 22:22
  • 2
    If anyone is trying to get rid of the JSLint error on this, Just change [,null] into [undefined, null] – Aaron Springer Jun 28 '13 at 13:09
  • This returns string 'null' instead of real null. This is absolutely fatal in shorthand conditions like `if (getUrlParameter('test'))`. That will ALWAYS pass. Solution from @radicand is better. – Jan Peša Feb 07 '14 at 13:03
294

Below is what I have created from the comments here, as well as fixing bugs not mentioned (such as actually returning null, and not 'null'):

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
radicand
  • 6,068
  • 3
  • 27
  • 22
  • 6
    How about adding `new` in front of RegExp? Less lint warnings. – ripper234 Apr 04 '12 at 09:49
  • 18
    This should be the accepted answer. Getting real null back instead of "null" is way better. – Art Aug 22 '12 at 05:14
  • 11
    If anyone needs this converted to coffeescript: getURLParameter: (name) -> return decodeURIComponent((new RegExp("[?|&]#{name}=([^&;]+?)(&|##|;|$)").exec(location.search) || [null,""] )[1].replace(/\+/g, '%20'))||null; – Redbeard Sep 10 '12 at 06:09
  • you don't need to use return in coffeescript... why does everyone keep doing that – mrbrdo Feb 14 '13 at 19:01
  • For parameters that aren't followed by equals sign, which is perfectly legal, this will return null. Example, `?a=1&b&c`. You might want to return empty string for c, and undefined for something that isn't there at all for example d. I end up using `function getParam(param) { var query = new RegExp('[?|&]'+param+'(=)?(.*?)(&|#|$)'); var search = document.URL.match(query); if (search){ return decodeURIComponent(search[2]); } } ` – Kevin M May 08 '13 at 00:05
  • 1
    @Redbeard - Shouldn't your function have a '=' sign after method definition instead of a double colon? – Zippie Sep 16 '13 at 14:27
  • @radicand doesn't work (chrome latest) - http://jsfiddle.net/orwellophile/4JhHA/ just returns null – Orwellophile Dec 06 '13 at 13:05
  • @Orwellophile, it does work, your test code is bad (location.search is a string of the latter half of the URL bar, whereas your code should just use "_location"). See http://jsfiddle.net/drWKu/ – radicand Dec 06 '13 at 13:34
  • Ahh, indeed. My bad. Well, good to have a fiddle, and good to have a version that can operate on (optional) URLs other than current location. – Orwellophile Dec 09 '13 at 08:02
  • This works much better than the above solution in my testing. – peelman Jan 20 '14 at 16:46
  • my code was breaking when there was no location.search, I am using `return (location.search.length?decodeURIComponent((new RegExp("[?|&]"+str+"=([^&;]+?)(&|#|;|$)").exec(location.search)||[,""])[1].replace(/\+/g,"%20")):"");` – ajax333221 Mar 28 '14 at 21:00
  • 1
    This is the only version of a get-URL-parameter function that works for me with a UTF8 string. – certainlyakey Jul 29 '14 at 05:55
107

What you really want is the jQuery URL Parser plugin. With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this:

$.url().param('foo');

If you want an object with parameter names as keys and parameter values as values, you'd just call param() without an argument, like this:

$.url().param();

This library also works with other urls, not just the current one:

$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes

Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc:

var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'

It has other features as well, check out its homepage for more docs and examples.

Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. Depending on the answer, code from other answers can return 'null' instead of null, doesn't work with empty parameters (?foo=&bar=x), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc.

Use an actual URI parser, don't invent your own.

For those averse to jQuery, there's a version of the plugin that's pure JS.

Lucas
  • 6,328
  • 8
  • 37
  • 49
  • 23
    The question is "get URL parameter with jQuery". My answer answers the question. Other answers instruct the user to basically write his own URI parser for this specific use case, which is a terrible idea. Parsing URI's is more complicated that people think. – Lucas Jun 01 '12 at 17:35
  • 2
    This is the answer I was looking for, and is very jQuery-ish, unlike some of the other answers. – Ehtesh Choudhury Apr 02 '13 at 17:01
  • Does the plugin handles the URI encoding or do I have to decode it manually? – Roberto Linares May 16 '13 at 16:08
  • The question says "javascript" (I think it means the DOM directly) or jQuery. So any of the others will do. – brunoais Nov 13 '13 at 08:47
43

If you don't know what the URL parameters will be and want to get an object with the keys and values that are in the parameters, you can use this:

function getParameters() {
  var searchString = window.location.search.substring(1),
      params = searchString.split("&"),
      hash = {};

  if (searchString == "") return {};
  for (var i = 0; i < params.length; i++) {
    var val = params[i].split("=");
    hash[unescape(val[0])] = unescape(val[1]);
  }
  return hash;
}

Calling getParameters() with a url like /posts?date=9/10/11&author=nilbus would return:

{
  date:   '9/10/11',
  author: 'nilbus'
}

I won't include the code here since it's even farther away from the question, but weareon.net posted a library that allows manipulation of the parameters in the URL too:

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Edward Anderson
  • 13,591
  • 4
  • 52
  • 48
  • 1
    Yes, this is better to obtain all the params. All the other solutions listed here repeat the regex for each param. – Bernard Feb 06 '12 at 11:05
  • This function returns an awkward object: `{"": undefined}` when the URL is void of parameters. Best to return an empty object by using `if(searchString=='') return {};` directly after the `searchString` assignment. – Jordan Arsenault Jul 01 '13 at 23:55
40

You can use the browser native location.search property:

function getParameter(paramName) {
  var searchString = window.location.search.substring(1),
      i, val, params = searchString.split("&");

  for (i=0;i<params.length;i++) {
    val = params[i].split("=");
    if (val[0] == paramName) {
      return unescape(val[1]);
    }
  }
  return null;
}

But there are some jQuery plugins that can help you:

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
25

Based on the 999's answer:

function getURLParameter(name) {
    return decodeURIComponent(
        (location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
    );  
}

Changes:

  • decodeURI() is replaced with decodeURIComponent()
  • [?|&] is added at the beginning of the regexp
Community
  • 1
  • 1
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • 3
    Might be helpful for others if you could explain why you made these changes. Thx – Timm Mar 05 '12 at 09:26
  • 3
    Doesn't handle empty params: `?a=&b=1`. Better regexp would be: `"[?&]"+name+"=([^&]*)"` – serg Mar 23 '12 at 22:34
6

Need to add the i parameter to make it case insensitive:

  function getURLParameter(name) {
    return decodeURIComponent(
      (RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
    );
  }
Scott Wojan
  • 89
  • 1
  • 2
3

After reading all of the answers I ended up with this version with + a second function to use parameters as flags

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

function isSetURLParameter(name) {
    return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}
Neon
  • 293
  • 1
  • 2
  • 8
  • 2
    Good Answer, just one warning however. Per JSHint, [,""] can cause issues for older browsers. So, use instead [null,""] or [undefined,""]. There are still some of us unhappy few who support IE8 and dare I say it IE7. – Delicia Brummitt Jun 25 '13 at 20:20
2
$.urlParam = function(name){
  var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href); 
  return (results !== null) ? results[1] : 0;
}

$.urlParam("key");
j0k
  • 22,600
  • 28
  • 79
  • 90
Yoshi
  • 412
  • 3
  • 6
2

For example , a function which returns value of any parameters variable.

function GetURLParameter(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}​

And this is how you can use this function assuming the URL is,

"http://example.com/?technology=jquery&blog=jquerybyexample".

var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');

So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample".

Rubyist
  • 6,486
  • 10
  • 51
  • 86
2

You should not use jQuery for something like this!
The modern way is to use small reusable modules through a package-manager like Bower.

I've created a tiny module that can parse the query string into an object. Use it like this:

// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå
Sindre Sorhus
  • 62,972
  • 39
  • 168
  • 232
  • If you're saying it's not modern to have a framework, that's fine. But in my opinion frameworks really do have their place. jQuery is looking less and less pretty to me though. – Lodewijk Aug 04 '14 at 04:26
0

There's a lot of buggy code here and regex solutions are very slow. I found a solution that works up to 20x faster than the regex counterpart and is elegantly simple:

    /*
    *   @param      string      parameter to return the value of.
    *   @return     string      value of chosen parameter, if found.
    */
    function get_param(return_this)
    {
        return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.

        var url = window.location.href;                                   // Get the URL.
        var parameters = url.substring(url.indexOf("?") + 1).split("&");  // Split by "param=value".
        var params = [];                                                  // Array to store individual values.

        for(var i = 0; i < parameters.length; i++)
            if(parameters[i].search(return_this + "=") != -1)
                return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");

        return "Parameter not found";
    }

console.log(get_param("parameterName"));

Regex is not the be-all and end-all solution, for this type of problem simple string manipulation can work a huge amount more efficiently. Code source.

0
<script type="text/javascript">
function getURLParameter(name) {
        return decodeURIComponent(
            (location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
        );
    }

</script>

getURLParameter(id) or getURLParameter(Id) Works the same : )

Baby Groot
  • 4,637
  • 39
  • 52
  • 71
Kotrim
  • 9
  • 1
0

jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null){
       return null;
    }
    else{
       return results[1] || 0;
    }
}

example.com?param1=name&param2=&id=6

$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null

//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));  
//output: Gold%20Coast

console.log(decodeURIComponent($.urlParam('city'))); 
//output: Gold Coast
-1

I created a simple function to get URL parameter in JavaScript from a URL like this:

.....58e/web/viewer.html?page=*17*&getinfo=33


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

OUTPUT: 18

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Code Spy
  • 9,626
  • 4
  • 66
  • 46
  • 2
    Be careful when posting copy and paste boilerplate/verbatim answers to multiple questions, these tend to be flagged as "spammy" by the community. If you're doing this then it usually means the questions are duplicates so flag them as such instead: http://stackoverflow.com/a/11808489/419 – Kev Aug 04 '12 at 17:07
-1

Just in case you guys have the url like localhost/index.xsp?a=1#something and you need to get the param not the hash.

var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
    q = q.split('&');
    for(var i = 0; i < q.length; i++){
        hash = q[i].split('=');
        anchor = hash[1].split('#');
        vars.push(anchor[0]);
        vars[hash[0]] = anchor[0];
    }
}
James Wiseman
  • 29,946
  • 17
  • 95
  • 158
Ancyent
  • 27
  • 1
  • 8
-1

Slight modification to the answer by @pauloppenheim , as it will not properly handle parameter names which can be a part of other parameter names.

Eg: If you have "appenv" & "env" parameters, redeaing the value for "env" can pick-up "appenv" value.

Fix:

var urlParamVal = function (name) {
    var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
    return result ? decodeURIComponent(result[2]) : "";
};
lasantha
  • 825
  • 8
  • 7
-1
function getURLParameters(paramName) 
{
        var sURL = window.document.URL.toString();  
    if (sURL.indexOf("?") > 0)
    {
       var arrParams = sURL.split("?");         
       var arrURLParams = arrParams[1].split("&");      
       var arrParamNames = new Array(arrURLParams.length);
       var arrParamValues = new Array(arrURLParams.length);     
       var i = 0;
       for (i=0;i<arrURLParams.length;i++)
       {
        var sParam =  arrURLParams[i].split("=");
        arrParamNames[i] = sParam[0];
        if (sParam[1] != "")
            arrParamValues[i] = unescape(sParam[1]);
        else
            arrParamValues[i] = "No Value";
       }

       for (i=0;i<arrURLParams.length;i++)
       {
                if(arrParamNames[i] == paramName){
            //alert("Param:"+arrParamValues[i]);
                return arrParamValues[i];
             }
       }
       return "No Parameters Found";
    }

}
Dhiral Pandya
  • 10,311
  • 4
  • 47
  • 47
-2

This may help.

<script type="text/javascript">
    $(document).ready(function(){
        alert(getParameterByName("third"));
    });
    function getParameterByName(name){
        var url     = document.URL,
            count   = url.indexOf(name);
            sub     = url.substring(count);
            amper   = sub.indexOf("&"); 

        if(amper == "-1"){
            var param = sub.split("=");
            return param[1];
        }else{
            var param = sub.substr(0,amper).split("=");
            return param[1];
        }

    }
</script>