Get escaped URL parameter

366,432

Solution 1

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;
//=> æøå

Solution 2

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

Solution 3

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

Solution 4

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.

Solution 5

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:

Share:
366,432

Related videos on Youtube

Sindre Sorhus
Author by

Sindre Sorhus

Updated on August 18, 2020

Comments

  • Sindre Sorhus
    Sindre Sorhus over 3 years

    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.

    • Artem Barger
      Artem Barger over 14 years
    • Kevin M
      Kevin M
      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.
  • Sébastien RoccaSerra
    Sébastien RoccaSerra about 13 years
    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!
  • Damien
    Damien over 12 years
    this function returns 'null' instead of null when the parameter is not defined... the joy of js...
  • perfectionist
    perfectionist about 12 years
    you may want "decodeURIComponent()" instead of "decodeURI()", especially if you are passing interesting data like return URLs in as a URL parameter
  • Timm
    Timm about 12 years
    Might be helpful for others if you could explain why you made these changes. Thx
  • user2012801
    user2012801 about 12 years
    Doesn't handle empty params: ?a=&b=1. Better regexp would be: "[?&]"+name+"=([^&]*)"
  • ripper234
    ripper234 about 12 years
    How about adding new in front of RegExp? Less lint warnings.
  • Stephan B.
    Stephan B. almost 12 years
    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.
  • standup75
    standup75 almost 12 years
    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] )
  • Kev
    Kev over 11 years
    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: stackoverflow.com/a/11808489/419
  • Naidan
    Naidan over 11 years
    This should be the accepted answer. Getting real null back instead of "null" is way better.
  • Sanjeev Kumar Dangi
    Sanjeev Kumar Dangi over 11 years
    This fixes 'null' instead of null issue: function getURLParameter(name) { var param = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]; return (param?:decodeURI(param):param); } }
  • Redbeard
    Redbeard over 11 years
    If anyone needs this converted to coffeescript: getURLParameter: (name) -> return decodeURIComponent((new RegExp("[?|&]#{name}=([^&;]+?)(&|##|;|$)").exec(location.sea‌​rch) || [null,""] )[1].replace(/\+/g, '%20'))||null;
  • Timmmm
    Timmmm over 11 years
    This is much cleaner and more readable (and probably more bug-free) than all those regex one-liners.
  • freedev
    freedev over 11 years
    I'll suggest to use decodeURIComponent() instead of unescape()
  • mrbrdo
    mrbrdo about 11 years
    you don't need to use return in coffeescript... why does everyone keep doing that
  • Lukasz 'Severiaan' Grela
    Lukasz 'Severiaan' Grela about 11 years
    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; }
  • Ehtesh Choudhury
    Ehtesh Choudhury about 11 years
    This is the answer I was looking for, and is very jQuery-ish, unlike some of the other answers.
  • Kevin M
    Kevin M almost 11 years
    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]); } }
  • Roberto Linares
    Roberto Linares almost 11 years
    Does the plugin handles the URI encoding or do I have to decode it manually?
  • blue-sky
    blue-sky almost 11 years
    This does'nt seem to work with URL : 'localhost:8888/?version=fghdfghd' , this accepted answer does : stackoverflow.com/questions/979975/…
  • Aaron Springer
    Aaron Springer almost 11 years
    If anyone is trying to get rid of the JSLint error on this, Just change [,null] into [undefined, null]
  • Zippie
    Zippie over 10 years
    @Redbeard - Shouldn't your function have a '=' sign after method definition instead of a double colon?
  • brunoais
    brunoais over 10 years
    The question says "javascript" (I think it means the DOM directly) or jQuery. So any of the others will do.
  • brunoais
    brunoais over 10 years
    +1 this works for modern browsers but some devs need to work with... :| IE8 :S.
  • Orwellophile
    Orwellophile over 10 years
    @radicand doesn't work (chrome latest) - jsfiddle.net/orwellophile/4JhHA just returns null
  • radicand
    radicand over 10 years
    @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 jsfiddle.net/drWKu
  • Orwellophile
    Orwellophile over 10 years
    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.
  • peelman
    peelman over 10 years
    This works much better than the above solution in my testing.
  • Jan Peša
    Jan Peša about 10 years
    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.
  • ajax333221
    ajax333221 about 10 years
    my code was breaking when there was no location.search, I am using return (location.search.length?decodeURIComponent((new RegExp("[?|&]"+str+"=([^&;]+?)(&|#|;|$)").exec(location.sear‌​ch)||[,""])[1].repla‌​ce(/\+/g,"%20")):"")‌​;
  • certainlyakey
    certainlyakey almost 10 years
    This is the only version of a get-URL-parameter function that works for me with a UTF8 string.