Get escaped URL parameter
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:
Related videos on Youtube
Sindre Sorhus
Updated on August 18, 2020Comments
-
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 over 14 years
-
Kevin MThe 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 likeescape()
and changing thedecodeURIComponent()
call to anunescape()
should help.
-
-
Sébastien RoccaSerra about 13 yearsWith
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 over 12 yearsthis function returns 'null' instead of null when the parameter is not defined... the joy of js...
-
perfectionist about 12 yearsyou may want "decodeURIComponent()" instead of "decodeURI()", especially if you are passing interesting data like return URLs in as a URL parameter
-
Timm about 12 yearsMight be helpful for others if you could explain why you made these changes. Thx
-
user2012801 about 12 yearsDoesn't handle empty params:
?a=&b=1
. Better regexp would be:"[?&]"+name+"=([^&]*)"
-
ripper234 about 12 yearsHow about adding
new
in front of RegExp? Less lint warnings. -
Stephan B. almost 12 yearsThe 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 almost 12 yearsThis 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 over 11 yearsBe 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 over 11 yearsThis should be the accepted answer. Getting real null back instead of "null" is way better.
-
Sanjeev Kumar Dangi over 11 yearsThis fixes 'null' instead of null issue: function getURLParameter(name) { var param = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]; return (param?:decodeURI(param):param); } }
-
Redbeard over 11 yearsIf anyone needs this converted to coffeescript: getURLParameter: (name) -> return decodeURIComponent((new RegExp("[?|&]#{name}=([^&;]+?)(&|##|;|$)").exec(location.search) || [null,""] )[1].replace(/\+/g, '%20'))||null;
-
Timmmm over 11 yearsThis is much cleaner and more readable (and probably more bug-free) than all those regex one-liners.
-
freedev over 11 yearsI'll suggest to use decodeURIComponent() instead of unescape()
-
mrbrdo about 11 yearsyou don't need to use return in coffeescript... why does everyone keep doing that
-
Lukasz 'Severiaan' Grela about 11 yearsDown 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 about 11 yearsThis is the answer I was looking for, and is very jQuery-ish, unlike some of the other answers.
-
Kevin M almost 11 yearsFor 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 usingfunction getParam(param) { var query = new RegExp('[?|&]'+param+'(=)?(.*?)(&|#|$)'); var search = document.URL.match(query); if (search){ return decodeURIComponent(search[2]); } }
-
Roberto Linares almost 11 yearsDoes the plugin handles the URI encoding or do I have to decode it manually?
-
blue-sky almost 11 yearsThis does'nt seem to work with URL : 'localhost:8888/?version=fghdfghd' , this accepted answer does : stackoverflow.com/questions/979975/…
-
Aaron Springer almost 11 yearsIf anyone is trying to get rid of the JSLint error on this, Just change [,null] into [undefined, null]
-
Zippie over 10 years@Redbeard - Shouldn't your function have a '=' sign after method definition instead of a double colon?
-
brunoais over 10 yearsThe question says "javascript" (I think it means the DOM directly) or jQuery. So any of the others will do.
-
brunoais over 10 years+1 this works for modern browsers but some devs need to work with... :| IE8 :S.
-
Orwellophile over 10 years@radicand doesn't work (chrome latest) - jsfiddle.net/orwellophile/4JhHA just returns null
-
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 over 10 yearsAhh, 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 over 10 yearsThis works much better than the above solution in my testing.
-
Jan Peša about 10 yearsThis 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 about 10 yearsmy 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")):"");
-
certainlyakey almost 10 yearsThis is the only version of a get-URL-parameter function that works for me with a UTF8 string.