689

I have seen lots of jQuery examples where parameter size and name are unknown.

My URL is only going to ever have 1 string:

http://example.com?sent=yes

I just want to detect:

  1. Does sent exist?
  2. Is it equal to "yes"?
simhumileco
  • 21,911
  • 14
  • 106
  • 90
LeBlaireau
  • 14,709
  • 30
  • 95
  • 169

33 Answers33

1317

Best solution here.

var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
};

And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample.

var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
Daniel Ruf
  • 6,949
  • 10
  • 55
  • 108
Sameer Kazi
  • 15,421
  • 2
  • 31
  • 46
  • 11
    Thanks! But when copying this, I found a nasty surprise, involving a zero-width whitespace (\u200b) towards the end there. Making the script have an invisible syntax error. – Christofer Ohlsson Aug 12 '14 at 08:54
  • How to convert the "+" inside parameter value into whitespaces? – albusshin Nov 11 '14 at 06:42
  • 1
    Be careful, `;` is a [legal delimeter](https://en.wikipedia.org/wiki/Query_string#Structure) which this doesn't account for. – smoak Dec 05 '14 at 19:58
  • 14
    Return a `false` or `null` for empty search – Stefano Caravana Feb 09 '15 at 14:06
  • 5
    This solution works pretty well for me I've just used var sPageURL = decodeURI(window.location.search.substring(1)); to convert %20 characters into white spaces and also I return an empty string instead of nothing if the parameter is not matched. – Christophe Feb 11 '15 at 13:44
  • 1
    As per http://stackoverflow.com/questions/8486099/how-do-i-parse-a-url-query-parameters-in-javascript, location.search won't work for hash based routing (#) – Cody Moniz Apr 16 '15 at 19:01
  • 1
    To handle valueless params like `?param1&param2` modify the return to: `return sParameterName[1] === undefined ? true : sParameterName[1];` – sebt May 01 '15 at 15:28
  • I would use "=== sParam" vs "== sParam" otherwise sParam = 'true' would match everything. Besides, always using === is a good idea period. – chad May 06 '15 at 16:14
  • need to add `sPageURL=decodeURIComponent(sPageURL);` to have special chars like **space** and **"** displayed correctly – elsadek May 10 '15 at 05:56
  • Just to mention it - this script fragment also works without jQuery. – Remigius Stalder May 21 '15 at 09:12
  • 21
    I've updated the answer to include all the comments code changes above this comment. – Rob Evans Jul 28 '15 at 06:37
  • you can return empty string explicitly if no matches found - just before the last line of code. return ''; }; In that way all the code will return value – Lyubomir Velchev Oct 13 '15 at 20:40
  • 9
    The decoding should be done on the parameter value (as Iouri suggests). If the decoding is done on the url (as in the answer), it won't work correctly if there's an encoded `&` or `=` in a parameter value. – zakinster Dec 02 '15 at 13:46
  • 1
    I needed to get a certain param from api generated data that was unpredictably separated sometimes by a question mark and sometimes an ampersand. Replacing the third line of Kazi's code with this regex: sURLVariables = sPageURL.split(new RegExp('[\?&]')) works for me in that situation. – Rufus Jan 09 '16 at 22:28
  • 1
    Since query string parameters are case insensitive, I think it would be better if when looking for a match with the parameter name provided the strings that are compared should be transformed to lower- or uppercase, e.g. if (sParameterName[0].toLowerCase() === sParam.toLowerCase()) – Yulian Feb 08 '16 at 09:30
  • 3
    This doesn't seem to work for multivalued keys (like `?technology=jquery&technology=css`). – alexw Feb 13 '16 at 20:05
  • 2
    I added `return false;` at the end of the function. – Master DJon Jul 13 '16 at 23:26
  • 1
    You just saved my day. Thanks – KristCont Nov 17 '16 at 00:46
  • 3
    I think you shoud call decodeURIComponent on sParameterName[0] before comparing and on sParameterName[1] before returning, not on the whole string... What happens if a parameter name or value has an (encoded) '&' or '=' in it? You will do the wrong split! – xzoert Jan 25 '17 at 11:05
  • 1
    I have some problem with this script so I have found better here http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Stanislav Potapenko Feb 02 '17 at 17:22
  • 2
    It's actually wrong; you should urldecode parameters AFTER you have split the string, not before. Otherwise it will freak out if '&' or '=' are encoded there in the actual parameters. – Ivan Skalauh Mar 11 '17 at 19:55
  • you should use var window.location['pathname'] instead of window.location.search.substring(1) or else this will not work. – Florin Andrei Mar 27 '17 at 22:21
  • It works but is very inefficient. You're performing all the same work every time. Create an object that has a "params" list and that function as a method. When you call the function, populate the list of params. Then have a getter which returns items from the list. If you're going to write a function that does the same thing each time, use RegEx, far faster, far more efficient – Paul Allsopp Feb 22 '18 at 17:23
  • `var url = ` **new URI** `( ` **'http://example.com?sent=yes'** `);` `var sendval = url.` **searchParams** ` (` 'sent' );` and you're done! I down voted this. Even if it's nice tempting and a good coding practice to write ya one homebrew function. Primary make use of functions ya library / framework offers, until you've good reason to do not. – Nadu Mar 03 '18 at 18:34
  • I am missing something, what part of it is jquery, isnt this plain javascript? – user734028 May 05 '18 at 05:45
  • 1
    Why do you name the function twice? Just delete the `var getUrlParameter = ` if you want to keep the function name – Penguin9 Sep 07 '18 at 13:18
  • Fix @Nadu comment: `var url = new URL( 'http://example.com?sent=yes' ), sendval = url. searchParams.get('sent')` see https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#Example – nicolallias Sep 19 '18 at 16:05
  • in my opinion, the code will be perfect if you change the IF condition to be : ` if (decodeURIComponent(sParameterName[0]) === sParam || sParameterName[0] === sParam) ` so that if we compare the variables that are already encoded as the arrays the condition "IF" will pass – Abdallah Arffak Dec 08 '18 at 12:10
  • `sParameterName[0]` should be `decodeURIComponent(sParameterName[0])` – ikegami Mar 31 '19 at 09:05
  • 1
    Does not work for this : ?u=0d84c05f8cf68bda7ea336e194bfa0dfk`=`&t=post Note the highlight character(=) it is the part of the value and is not counting that. – MR_AMDEV Jul 30 '19 at 19:58
  • @MR_AMDEV if `=` is part of the string value then it should be encoded as `%3D`. – user7290573 Oct 09 '20 at 10:52
407

Solution from 2021

We have: http://example.com?sent=yes

let searchParams = new URLSearchParams(window.location.search)

Does sent exist?

searchParams.has('sent') // true

Is it equal to "yes"?

let param = searchParams.get('sent')

and then just compare it.

Optio
  • 5,239
  • 2
  • 15
  • 28
  • 19
    i think this is not supported across browsers so why should one use it? reference - https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams – p_champ Mar 24 '17 at 06:24
  • 1
    @p_champ you are right. But you can use [polyfill for URLSearchParams](https://github.com/WebReflection/url-search-params) – Optio Mar 24 '17 at 12:26
  • 4
    currently not working in IE / Edge, so do feature detection: `if ('URLSearchParams' in window) { // Browser supports URLSearchParams}` [See here](https://developers.google.com/web/updates/2016/01/urlsearchparams?hl=en) – mfgmicha Jan 10 '18 at 13:19
  • 6
    Good enough for me and my intended audience. https://caniuse.com/#feat=urlsearchparams – jontsai Feb 03 '18 at 22:52
  • Note this solutions is not clean code. It'll work **for get only**. Try param.toString() on the current code. You'll get `http%3A%2F%2Fexample...` So if you need to change the URL or like to be the correct and avoiding this kinda type violate do it like this: Use `url=new URI(window.location.search)` Then `param = url.searchParams;` The rest of the code above is fine. – Nadu Mar 03 '18 at 18:10
  • 12
    @p_champ Edge got support in v17 (April 2018). Let IE die. – Ryan DuVal Jun 19 '19 at 03:57
  • 5
    This is a modern solution to a modern problem. – Matt Sep 30 '19 at 17:05
  • If only IE 11 had support for this feature, how nice that'd be!! :) – tonejac Mar 18 '20 at 16:00
  • 2
    According to the table linked by p_champ the only browser that doesn't support this at all is the InternetExplorer. All other current browsers can handle it. I like this solution as it is short and elegant. – Andreas Jul 16 '20 at 12:44
217

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 decodeURI(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
davidrl1000
  • 281
  • 1
  • 3
  • 15
  • 14
    Note: You need to decode in case there are special characters as parameter or Umlaute etc. So instead of `return results[1] || 0;` it should be `return decodeURI(results[1]) || 0;` – Avatar Dec 22 '15 at 15:14
  • Just curious, why does it need the `|| 0` part since there is already a check for the result, wouldn't it always return the match array ? – AirWick219 May 03 '16 at 14:41
  • @AirWick219 an appropriate failsafe. though redundant, never hurts to be cautious – zanderwar Oct 21 '16 at 07:00
  • 2
    Here is, most likely, the original source: https://www.sitepoint.com/url-parameters-jquery/ but this answer has some new ideas added – bgmCoder Jun 16 '17 at 22:34
  • In my url, the params I need are hiding behind a `#` and *then* a second `?`. How can I modify the regex to find `harry` in this url? `http://some.site.com/page.aspx?a=1&b=2&c=3&d=4#e=5&f=6?g=harry` – bgmCoder Jun 17 '17 at 16:05
  • @bgmCoder I hope you know by now why that wouldnt be possible? :D – Toby May 01 '18 at 13:32
  • @Tobias - not true. I think I did figure out how to get that. If I remember right, I think I either regexed the last parameter or the entire url, – bgmCoder May 02 '18 at 15:30
  • 1
    Not sure it's worth using jQuery for this. – Quentin 2 Jul 18 '18 at 17:03
  • Are you sure you need decodeURI followed by decodeURIComponent too? – Quentin 2 Jul 18 '18 at 17:11
  • This is a good approach. Can you provide one for javascript instead of jquery? – MR_AMDEV Jul 30 '19 at 20:01
  • Meanwhile in 2020: Thank you for the correct regex - I was using an other one which did not work properly. Your's is working perfect for me! – JonSnow Jun 23 '20 at 16:27
  • There is a problem: try "?id=10&item_id=30" and then opposite - "?item_id=30&id=10". Compare results and you wull know something new ;-) – Igor Nov 23 '20 at 10:17
96

I always stick this as one line. Now params has the vars:

params={};location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k]=v})

multi-lined:

var params={};
window.location.search
  .replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
    params[key] = value;
  }
);

as a function

function getSearchParams(k){
 var p={};
 location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
 return k?p[k]:p;
}

which you could use as:

getSearchParams()  //returns {key1:val1, key2:val2}

or

getSearchParams("key1")  //returns val1
AwokeKnowing
  • 6,390
  • 7
  • 32
  • 43
  • Ugly hack that modifies the search string... but no external modules or jquery required. I like it. – Bryce Jun 10 '15 at 08:07
  • 5
    @Bryce It actually doesn't modify the search string. the .replace actually returns a new string and those returned strings are processed into the params object. – AwokeKnowing Jun 10 '15 at 17:56
  • Nice, short and, contrary to accepted solution, doesn't need to reparse url each time you need a value. Could be slightly improved with `replace(/[?&;]+([^=]+)=([^&;]*)/gi` to reconize ";" character as a separator too. – Le Droid Feb 05 '16 at 18:16
  • clear and painless one-liner, better than accepted answer for me, no extra libs. – Sam May 17 '16 at 10:02
  • This is what one would use if one uses hashes instead of GET-query delimiter (questionmark): ```var params={};window.location.hash.replace(/[#&]+([^=&]+)=([^&]*)/gi,function(str,key,value){params[key] = value;});``` This is useful for things such as AJAX where the hash in window is updated with ajax-requests but one also one the user to go to a uri containing a hash. – Tommie May 31 '16 at 09:29
  • @Tommie Thanks, I see the value in that if you happen to be structuring your hash values as url parameters. – AwokeKnowing May 31 '16 at 19:27
  • Nice answer, but it doesn't work with `?a_parameter`. It would be awesome if this produced `{'a_parameter' : null }` instead of `{}` – Henry Aug 31 '17 at 01:59
  • To pass typescript validation, the inner function should return a string. `function(s,k,v){p[k]=v; return v;})` – Sydwell Jan 19 '19 at 09:20
  • nice, but would be way better with more descriptive variables names – Oli Crt Oct 27 '20 at 14:42
51

Yet another alternative function...

function param(name) {
    return (location.search.split(name + '=')[1] || '').split('&')[0];
}
rodnaph
  • 1,169
  • 9
  • 11
  • name needs to be a string. Worked like a charm~ – mintedsky Mar 31 '17 at 13:48
  • 2
    This is my favorite. +1 Of note though this is an "ends with" type of search. For example, if you pass in "Phone" for the name, and there's also a field called "HomePhone" it may return the value of the wrong one if it comes first in the url. – efreed Sep 18 '17 at 14:47
  • 2
    This is wrong! For example `param('t') == param('sent') == 'yes'` in the OP example. Here's a fix: `return (location.search.split(new RegExp('[?&]' + name + '='))[1] || '').split('&')[0]`; Also note that you cannot tell if the param exists because you get empty string for missing parameters. – oriadam Jan 14 '18 at 12:55
  • Very simple and elegant. Works like a dream. Thank you. – Anjana Silva Apr 20 '18 at 10:08
  • // (to force the full key to exist instead of only the last part of the key) `return (location.search.split('?' + name + '=')[1] || location.search.split('&' + name + '=')[1] || '').split('&')[0];` – Aaron Apr 13 '19 at 14:44
47

May be its too late. But this method is very easy and simple

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>

<!-- URL:  www.example.com/correct/?message=done&year=1990 -->

<script type="text/javascript">
$(function(){
    $.url.attr('protocol')  // --> Protocol: "http"
    $.url.attr('path')      // --> host: "www.example.com"
    $.url.attr('query')         // --> path: "/correct/"
    $.url.attr('message')       // --> query: "done"
    $.url.attr('year')      // --> query: "1990"
});

UPDATE
Requires the url plugin : plugins.jquery.com/url
Thanks -Ripounet

Sariban D'Cl
  • 2,025
  • 2
  • 22
  • 38
  • 2
    Whoever decides on this should check the repo first. Usage has changed. $.url.attr('message') becomes $.url("query") and it only gives the full query! To get only one parameter I had to: $.url("query").split("=")[1] [url github link](https://github.com/websanova/js-url) – pseudozach Jul 12 '16 at 09:34
41

Using URLSearchParams:

var params = new window.URLSearchParams(window.location.search);
console.log(params.get('name'));

Be careful about the compatibility (Mostly it's fine, but IE and Edge, may be different story, check this for compatible reference: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)

Xin
  • 22,636
  • 12
  • 71
  • 68
39

Or you can use this neat little function, because why overcomplicated solutions?

function getQueryParam(param, defaultValue = undefined) {
    location.search.substr(1)
        .split("&")
        .some(function(item) { // returns first occurence and stops
            return item.split("=")[0] == param && (defaultValue = item.split("=")[1], true)
        })
    return defaultValue
}

which looks even better when simplified and onelined:

tl;dr one-line solution

var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
result:
queryDict['sent'] // undefined or 'value'

But what if you have got encoded characters or multivalued keys?

You better see this answer: How can I get query string values in JavaScript?

Sneak peak

"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> queryDict
a: ["1", "5", "t e x t"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]

> queryDict["a"][1] // "5"
> queryDict.a[1] // "5"
Community
  • 1
  • 1
Qwerty
  • 19,992
  • 16
  • 88
  • 107
  • 3
    string split is likely to be faster than regex too. Not that that is a factor considering the url would only be parsed once. – Patrick Apr 08 '16 at 01:05
  • This is the solution (the first one) that worked perfectly for me across browsers - thank you! – NickyTheWrench Jun 10 '19 at 18:03
  • 1
    @NickyTheWrench Great to hear that, thank you! Anyway, be aware that this is a very simple solution, if you get complicated url params that contain special characters, you better check the link provided. – Qwerty Jun 11 '19 at 15:02
  • @Qwerty yup - my use case is very simple where the parameter is always the same, etc (basically exactly what the OP asked for) Thanks again! – NickyTheWrench Jun 11 '19 at 18:37
  • The "return param" in the first example means the URL query parameter name is returned when it's not specified in the URL. This seems strange. – Bernard Vander Beken Oct 23 '19 at 11:03
  • 1
    @BernardVanderBeken Interesting, I fixed it, anyway, it's rather very dumb solution, the one at the bottom which supports encoded characters and arrays is much better. – Qwerty Oct 23 '19 at 11:41
12

This one is simple and worked for me

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

so if your url is http://www.yoursite.com?city=4

try this

console.log($.urlParam('city'));
Shuhad zaman
  • 2,298
  • 22
  • 25
10

Perhaps you might want to give Dentist JS a look? (disclaimer: I wrote the code)

code:

document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"

with Dentist JS, you can basically call the extract() function on all strings (e.g., document.URL.extract() ) and you get back a HashMap of all parameters found. It's also customizable to deal with delimiters and all.

Minified version < 1kb

fabsenet
  • 342
  • 1
  • 14
kelvintaywl
  • 185
  • 1
  • 8
5

I hope this will help.

 <script type="text/javascript">
   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;
   }

    $(window).load(function() {
      var param = getParameters();
      if (typeof param.sent !== "undefined") {
        // Do something.
      }
    });
</script>
kiamlaluno
  • 24,790
  • 16
  • 70
  • 85
Tarun Gupta
  • 5,881
  • 2
  • 36
  • 38
5

This might be overkill, but there is a pretty popular library now available for parsing URIs, called URI.js.

Example

var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow";
var components = URI.parse(uri);
var query = URI.parseQuery(components['query']);
document.getElementById("result").innerHTML = "URI = " + uri;
document.getElementById("result").innerHTML += "<br>technology = " + query['technology'];

// If you look in your console, you will see that this library generates a JS array for multi-valued queries!
console.log(query['technology']);
console.log(query['blog']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script>

<span id="result"></span>
alexw
  • 7,044
  • 6
  • 46
  • 81
5

function GetRequestParam(param)
{
 var res = null;
 try{
  var qs = decodeURIComponent(window.location.search.substring(1));//get everything after then '?' in URI
  var ar = qs.split('&');
  $.each(ar, function(a, b){
   var kv = b.split('=');
   if(param === kv[0]){
    res = kv[1];
    return false;//break loop
   }
  });
 }catch(e){}
 return res;
}
p_champ
  • 865
  • 1
  • 11
  • 20
4

Try this working demo http://jsfiddle.net/xy7cX/

API:

This should help :)

code

var url = "http://myurl.com?sent=yes"

var pieces = url.split("?");
alert(pieces[1] + " ===== " + $.inArray("sent=yes", pieces));
Tats_innit
  • 33,101
  • 9
  • 67
  • 75
  • 3
    only works for a single var -- the & would throw it off -- could be extended with regex – Alvin Aug 21 '14 at 18:24
4

So simple you can use any url and get value

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Usage Example

// query string: ?first=value1&second=&value2
var foo = getParameterByName('first'); // "value1"
var bar = getParameterByName('second'); // "value2" 

Note: If a parameter is present several times (?first=value1&second=value2), you will get the first value (value1) and second value as (value2).

ImBhavin95
  • 1,403
  • 2
  • 14
  • 25
3

There's this great library: https://github.com/allmarkedup/purl

which allows you to do simply

url = 'http://example.com?sent=yes';
sent = $.url(url).param('sent');
if (typeof sent != 'undefined') { // sent exists
   if (sent == 'yes') { // sent is equal to yes
     // ...
   }
}

The example is assuming you're using jQuery. You could also use it just as plain javascript, the syntax would then be a little different.

Michael Konečný
  • 1,458
  • 1
  • 15
  • 20
  • 1
    This library is not maintained any more, however I use it and it's great. Make sure you use param not attr to get those query string parameters, as the author has included in their example. – Action Dan Jun 03 '15 at 02:45
3
http://example.com?sent=yes

Best solution here.

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.href);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
};

With the function above, you can get individual parameter values:

getUrlParameter('sent');
Elia Weiss
  • 5,417
  • 8
  • 50
  • 81
Naami
  • 341
  • 3
  • 9
2

This will give you a nice object to work with

    function queryParameters () {
        var result = {};

        var params = window.location.search.split(/\?|\&/);

        params.forEach( function(it) {
            if (it) {
                var param = it.split("=");
                result[param[0]] = param[1];
            }
        });

        return result;
    }

And then;

    if (queryParameters().sent === 'yes') { .....
Brian F
  • 1,418
  • 1
  • 13
  • 22
2

This is based on Gazoris's answer, but URL decodes the parameters so they can be used when they contain data other than numbers and letters:

function urlParam(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    // Need to decode the URL parameters, including putting in a fix for the plus sign
    // https://stackoverflow.com/a/24417399
    return results ? decodeURIComponent(results[1].replace(/\+/g, '%20')) : null;
}
Community
  • 1
  • 1
Stephen Ostermiller
  • 18,578
  • 8
  • 74
  • 95
2

There is another example with using URI.js library.

Example answers the questions exactly as asked.

var url = 'http://example.com?sent=yes';
var urlParams = new URI(url).search(true);
// 1. Does sent exist?
var sendExists = urlParams.sent !== undefined;
// 2. Is it equal to "yes"?
var sendIsEqualtToYes = urlParams.sent == 'yes';

// output results in readable form
// not required for production
if (sendExists) {
  console.log('Url has "sent" param, its value is "' + urlParams.sent + '"');
  if (urlParams.sent == 'yes') {
    console.log('"Sent" param is equal to "yes"');
  } else {
    console.log('"Sent" param is not equal to "yes"');
  }
} else {
  console.log('Url hasn\'t "sent" param');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script>
userlond
  • 3,323
  • 2
  • 28
  • 45
1

Coffeescript version of Sameer's answer

getUrlParameter = (sParam) ->
  sPageURL = window.location.search.substring(1)
  sURLVariables = sPageURL.split('&')
  i = 0
  while i < sURLVariables.length
    sParameterName = sURLVariables[i].split('=')
    if sParameterName[0] == sParam
      return sParameterName[1]
    i++
stevenspiel
  • 4,740
  • 10
  • 51
  • 82
1

A slight improvement to Sameer's answer, cache params into closure to avoid parsing and looping through all parameters each time calling

var getURLParam = (function() {
    var paramStr = decodeURIComponent(window.location.search).substring(1);
    var paramSegs = paramStr.split('&');
    var params = [];
    for(var i = 0; i < paramSegs.length; i++) {
        var paramSeg = paramSegs[i].split('=');
        params[paramSeg[0]] = paramSeg[1];
    }
    console.log(params);
    return function(key) {
        return params[key];
    }
})();
streaver91
  • 734
  • 1
  • 7
  • 10
1

I use this and it works. http://codesheet.org/codesheet/NF246Tzs

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


var first = getUrlVars()["id"];
studio-klik
  • 178
  • 1
  • 3
1

With vanilla JavaScript, you could easily take the params (location.search), get the substring (without the ?) and turn it into an array, by splitting it by '&'.

As you iterate through urlParams, you could then split the string again with '=' and add it to the 'params' object as object[elmement[0]] = element[1]. Super simple and easy to access.

http://www.website.com/?error=userError&type=handwritten

            var urlParams = location.search.substring(1).split('&'),
                params = {};

            urlParams.forEach(function(el){
                var tmpArr = el.split('=');
                params[tmpArr[0]] = tmpArr[1];
            });


            var error = params['error'];
            var type = params['type'];
DDT
  • 256
  • 3
  • 11
1

What if there is & in URL parameter like filename="p&g.html"&uid=66

In this case the 1st function will not work properly. So I modified the code

function getUrlParameter(sParam) {
    var sURLVariables = window.location.search.substring(1).split('&'), sParameterName, i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
}
user562451
  • 65
  • 1
  • 8
1

Admittedly I'm adding my answer to an over-answered question, but this has the advantages of:

-- Not depending on any outside libraries, including jQuery

-- Not polluting global function namespace, by extending 'String'

-- Not creating any global data and doing unnecessary processing after match found

-- Handling encoding issues, and accepting (assuming) non-encoded parameter name

-- Avoiding explicit for loops

String.prototype.urlParamValue = function() {
    var desiredVal = null;
    var paramName = this.valueOf();
    window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
        var nameVal = currentValue.split('=');
        if ( decodeURIComponent(nameVal[0]) === paramName ) {
            desiredVal = decodeURIComponent(nameVal[1]);
            return true;
        }
        return false;
    });
    return desiredVal;
};

Then you'd use it as:

var paramVal = "paramName".urlParamValue() // null if no match
BaseZen
  • 8,306
  • 2
  • 31
  • 45
1

If you want to find a specific parameter from a specific url:

function findParam(url, param){
  var check = "" + param;
  if(url.search(check )>=0){
      return url.substring(url.search(check )).split('&')[0].split('=')[1];
  }
}  

var url = "http://www.yourdomain.com/example?id=1&order_no=114&invoice_no=254";  
alert(findParam(url,"order_no"));
Wahid Masud
  • 873
  • 9
  • 25
0

Another solution that uses jQuery and JSON, so you can access the parameter values through an object.

var loc = window.location.href;
var param = {};
if(loc.indexOf('?') > -1)
{
    var params = loc.substr(loc.indexOf('?')+1, loc.length).split("&");

    var stringJson = "{";
    for(var i=0;i<params.length;i++)
    {
        var propVal = params[i].split("=");
        var paramName = propVal[0];
        var value = propVal[1];
        stringJson += "\""+paramName+"\": \""+value+"\"";
        if(i != params.length-1) stringJson += ",";
    }
    stringJson += "}";
    // parse string with jQuery parseJSON
    param = $.parseJSON(stringJson);
}

Assuming your URL is http://example.com/?search=hello+world&language=en&page=3

After that it's only a matter of using the parameters like this:

param.language

to return

en

The most useful usage of this is to run it at page load and make use of a global variable to use the parameters anywhere you might need them.

If your parameter contains numeric values then just parse the value.

parseInt(param.page)

If there are no parameters param will just be an empty object.

Niksuski
  • 45
  • 4
-1
$.urlParam = function(name) {
  var results = new RegExp('[\?&amp;]' + name + '=([^&amp;#]*)').exec(window.location.href);
  return results[1] || 0;
}
kiamlaluno
  • 24,790
  • 16
  • 70
  • 85
Aftab Uddin
  • 149
  • 1
  • 3
  • & is wrongly encoded as "&" in above answer, refer to correct answer http://stackoverflow.com/a/25359264/73630 – Palani Dec 10 '14 at 02:44
-1

use this

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

Just wanted to show my codes:

function (name) {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  results = regex.exec(location.search);
  return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

}

  • 2
    You need to pad out the answer with an explanation on how this helps the OP (not that they need it since they have 24 other answers to choose from and have already solved their issue). – Bugs Feb 07 '17 at 08:11
-1

var RequestQuerystring;
(window.onpopstate = function () {
    var match,
        pl = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query = window.location.search.substring(1);

    RequestQuerystring = {};
    while (match = search.exec(query))
        RequestQuerystring[decode(match[1])] = decode(match[2]);
})();

RequestQuerystring is now an object with all you parameters

Mina Gabriel
  • 17,138
  • 23
  • 89
  • 118
-1

Get the param from a string:

Object.defineProperty(String.prototype, 'urlParam', {

    value: function (param) {

    "use strict";

    var str = this.trim();

    var regex = "[\?&]" + param + "=([^&#]*)";

    var results = new RegExp(regex, "i").exec(str);

    return (results !== null) ? results[1] : '';

    }
});

to use:

var src = 'http://your-url.com/?param=value'

console.log(src.urlParam(param)); // returns 'value'