By Sindre Sorhus

2009-09-10 07:46:19 8 Comments

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.


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.


@Reza Baradaran Gazorisangi 2014-08-18 08:48:52

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;
       return results[1] || 0;

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

//example params with spaces Coast
//output: Gold%20Coast

//output: Gold Coast

@Sindre Sorhus 2013-11-15 02:29:13

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

@Lodewijk 2014-08-04 04:26:21

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.

@Edward Anderson 2012-01-18 16:23:13

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 =,
      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 posted a library that allows manipulation of the parameters in the URL too:

@Bernard 2012-02-06 11:05:58

Yes, this is better to obtain all the params. All the other solutions listed here repeat the regex for each param.

@Jordan Arseno 2013-07-01 23:55:00

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.

@user2310887 2013-08-06 09:13:52

<script type="text/javascript">
function getURLParameter(name) {
        return decodeURIComponent(
            ("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]


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

@lasantha 2013-07-30 21:29:16

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.


var urlParamVal = function (name) {
    var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(;
    return result ? decodeURIComponent(result[2]) : "";

@George Anthony 2013-07-02 01:04:15

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


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.

@Neon 2013-05-06 18:22:07

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(||[,""])[1].replace(/\+/g, '%20'))||null;

function isSetURLParameter(name) {
    return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec( !== null)

@Delicia Brummitt 2013-06-25 20:20:14

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.

@Rubyist 2013-01-22 08:55:42

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

function GetURLParameter(sParam)
    var sPageURL =;
    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,


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".

@Scott Wojan 2012-12-18 14:48:31

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

  function getURLParameter(name) {
    return decodeURIComponent(
      (RegExp(name + '=' + '(.+?)(&|$)', 'i').exec( || [, ""])[1]

@Ancyent 2012-09-25 08:27:53

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[hash[0]] = anchor[0];

@Code Spy 2012-08-04 12:01:51

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


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


@Kev 2012-08-04 17:07:44

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:

@Ram Guiao 2012-09-13 01:34:12

This may help.

<script type="text/javascript">
    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];
            var param = sub.substr(0,amper).split("=");
            return param[1];


@Lyth 2012-09-25 08:00:17

This code is not tested well. Guess what happens with query ?twothrids=text

@Yoshi 2012-05-24 04:30:19

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


@Lucas 2012-06-01 00:18:54

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:


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:


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

$('#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('');
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 2012-06-01 17:35:39

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.

@Ehtesh Choudhury 2013-04-02 17:01:20

This is the answer I was looking for, and is very jQuery-ish, unlike some of the other answers.

@Roberto Linares 2013-05-16 16:08:05

Does the plugin handles the URI encoding or do I have to decode it manually?

@brunoais 2013-11-13 08:47:05

The question says "javascript" (I think it means the DOM directly) or jQuery. So any of the others will do.

@radicand 2012-01-06 20:28:37

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(||[,""])[1].replace(/\+/g, '%20'))||null;

@ripper234 2012-04-04 09:49:02

How about adding new in front of RegExp? Less lint warnings.

@Art 2012-08-22 05:14:33

This should be the accepted answer. Getting real null back instead of "null" is way better.

@Redbeard 2012-09-10 06:09:46

If anyone needs this converted to coffeescript: getURLParameter: (name) -> return decodeURIComponent((new RegExp("[?|&]#{name}=([^&;]+?)(&|##|;|$)").exec(location.sea‌​rch) || [null,""] )[1].replace(/\+/g, '%20'))||null;

@mrbrdo 2013-02-14 19:01:39

you don't need to use return in coffeescript... why does everyone keep doing that

@Kevin M 2013-05-08 00:05:37

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

@Zippie 2013-09-16 14:27:07

@Redbeard - Shouldn't your function have a '=' sign after method definition instead of a double colon?

@Orwellophile 2013-12-06 13:05:18

@radicand doesn't work (chrome latest) - just returns null

@radicand 2013-12-06 13:34:10

@Orwellophile, it does work, your test code is bad ( is a string of the latter half of the URL bar, whereas your code should just use "_location"). See

@Orwellophile 2013-12-09 08:02:26

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 2014-01-20 16:46:07

This works much better than the above solution in my testing.

@ajax333221 2014-03-28 21:00:01

my code was breaking when there was no, I am using return ( RegExp("[?|&]"+str+"=([^&;]+?)(&|#|;|$)").exec(location.sear‌​ch)||[,""])[1].repla‌​ce(/\+/g,"%20")):"")‌​;

@certainlyakey 2014-07-29 05:55:52

This is the only version of a get-URL-parameter function that works for me with a UTF8 string.

@Dhiral Pandya 2012-01-05 20:21:19

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]);
            arrParamValues[i] = "No Value";

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


@Eugene Yarmash 2011-12-22 13:58:25

Based on the 999's answer:

function getURLParameter(name) {
    return decodeURIComponent(


  • decodeURI() is replaced with decodeURIComponent()
  • [?|&] is added at the beginning of the regexp

@Timm 2012-03-05 09:26:12

Might be helpful for others if you could explain why you made these changes. Thx

@serg 2012-03-23 22:34:22

Doesn't handle empty params: ?a=&b=1. Better regexp would be: "[?&]"+name+"=([^&]*)"

@James 2009-09-10 08:38:09

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

@Sébastien RoccaSerra 2011-04-27 10:07:28

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 2011-12-21 15:18:51

this function returns 'null' instead of null when the parameter is not defined... the joy of js...

@perfectionist 2012-02-27 13:14:45

you may want "decodeURIComponent()" instead of "decodeURI()", especially if you are passing interesting data like return URLs in as a URL parameter

@standup75 2012-06-07 16:39:59

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(||[,""])[1] )

@Sanjeev Kumar Dangi 2012-08-31 11:59:03

This fixes 'null' instead of null issue: function getURLParameter(name) { var param = (RegExp(name + '=' + '(.+?)(&|$)').exec(||[,null])[1]; return (param?:decodeURI(param):param); } }

@Lukasz 'Severiaan' Grela 2013-02-28 07:56:50

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(; if(!!p) { p = decodeURI(p[1]); } return p; }

@blue-sky 2013-05-18 22:22:16

This does'nt seem to work with URL : 'localhost:8888/?version=fghdfghd' , this accepted answer does :…

@Aaron Springer 2013-06-28 13:09:43

If anyone is trying to get rid of the JSLint error on this, Just change [,null] into [undefined, null]

@smajl 2014-02-07 13:03:45

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.

@CMS 2009-09-10 07:51:44

You can use the browser native property:

function getParameter(paramName) {
  var searchString =,
      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:

@Timmmm 2012-09-20 09:47:56

This is much cleaner and more readable (and probably more bug-free) than all those regex one-liners.

@freedev 2013-01-28 13:53:58

I'll suggest to use decodeURIComponent() instead of unescape()

@brunoais 2013-11-13 08:48:32

+1 this works for modern browsers but some devs need to work with... :| IE8 :S.

Related Questions

Sponsored Content

58 Answered Questions

[SOLVED] How to get the value from the GET parameters?

24 Answered Questions

[SOLVED] Get the current URL with JavaScript?

  • 2009-06-23 19:26:45
  • dougoftheabaci
  • 2843426 View
  • 3027 Score
  • 24 Answer
  • Tags:   javascript url

18 Answered Questions

[SOLVED] What is the maximum length of a URL in different browsers?

  • 2009-01-06 16:14:30
  • Sander Versluys
  • 1265109 View
  • 4870 Score
  • 18 Answer
  • Tags:   http url browser

15 Answered Questions

18 Answered Questions

[SOLVED] Encode URL in JavaScript?

17 Answered Questions

[SOLVED] How do I modify the URL without reloading the page?

23 Answered Questions

[SOLVED] How to change the URI (URL) for a remote Git repository?

  • 2010-03-12 12:48:47
  • e-satis
  • 1675533 View
  • 3960 Score
  • 23 Answer
  • Tags:   git url git-remote

32 Answered Questions

[SOLVED] What is the difference between a URI, a URL and a URN?

  • 2008-10-06 21:26:58
  • Sean McMains
  • 1152777 View
  • 4398 Score
  • 32 Answer
  • Tags:   http url uri urn rfc3986

73 Answered Questions

[SOLVED] How can I get query string values in JavaScript?

32 Answered Questions

[SOLVED] Get current URL with jQuery?

  • 2009-01-02 06:42:54
  • venkatachalam
  • 2160811 View
  • 1842 Score
  • 32 Answer
  • Tags:   javascript jquery url

Sponsored Content