792

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
35.2k18 gold badges147 silver badges125 bronze badges
asked Oct 21, 2013 at 9:55
6

35 Answers 35

1
2
1455

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 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');
Derek Adair
22k31 gold badges101 silver badges134 bronze badges
answered Feb 20, 2014 at 9:12
Sign up to request clarification or add additional context in comments.

30 Comments

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.
Return a false or null for empty search
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.
I've updated the answer to include all the comments code changes above this comment.
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.
|
622

Solution from 2025 <!-- removing the "the" helps readability. -->

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.

Last, if you have multiple entries for the same parameter (like ?id=1&id=2), you can use

let param = searchParams.getAll('id')

and it will return a list of values.

answered Feb 20, 2017 at 20:02

12 Comments

i think this is not supported across browsers so why should one use it? reference - developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
currently not working in IE / Edge, so do feature detection: if ('URLSearchParams' in window) { // Browser supports URLSearchParams} See here
Good enough for me and my intended audience. caniuse.com/#feat=urlsearchparams
@p_champ Edge got support in v17 (April 2018). Let IE die.
This is a modern solution to a modern problem.
|
237

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
4701 gold badge6 silver badges20 bronze badges
answered Aug 18, 2014 at 8:39

12 Comments

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;
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 an appropriate failsafe. though redundant, never hurts to be cautious
Here is, most likely, the original source: sitepoint.com/url-parameters-jquery but this answer has some new ideas added
Not sure it's worth using jQuery for this.
|
109

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
answered Nov 4, 2014 at 20:35

2 Comments

gives undefined for https://www.npmjs.com/package/js-string-helper?fbclid=IwAR1kXjYCXYwo3APfeGgKIhZNteim7k5lv8LUI1epkV1FWIReU-kX4uxghQM
@MdSifatulIslam, that line returns 'undefined' but at that point the var params is defined as {fbclid: 'IwAR1kXjYCXYwo3APfeGgKIhZNteim7k5lv8LUI1epkV1FWIReU-kX4uxghQM'} which you can use.
54

Yet another alternative function...

function param(name) {
 return (location.search.split(name + '=')[1] || '').split('&')[0];
}
answered Sep 29, 2016 at 10:51

2 Comments

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.
// (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];
50

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)

answered Aug 30, 2018 at 5:39

1 Comment

URLSearchParams replaces special character "+" with a space. So if your url param has a "+" in it, it will be replaced.
48

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

answered Mar 25, 2015 at 10:48

1 Comment

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
41

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"
answered Jul 14, 2015 at 16:17

6 Comments

string split is likely to be faster than regex too. Not that that is a factor considering the url would only be parsed once.
This is the solution (the first one) that worked perfectly for me across browsers - thank you!
@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 yup - my use case is very simple where the parameter is always the same, etc (basically exactly what the OP asked for) Thanks again!
@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.
|
14

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'));
answered Oct 25, 2016 at 6:59

Comments

12

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
3843 silver badges15 bronze badges
answered Nov 3, 2014 at 0:51

Comments

6

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>
avpaderno
30k17 gold badges80 silver badges95 bronze badges
answered Jan 8, 2014 at 10:01

Comments

5

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));
answered Oct 21, 2013 at 10:00

1 Comment

only works for a single var -- the & would throw it off -- could be extended with regex
5

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') { .....
answered Aug 22, 2014 at 5:19

1 Comment

split(/\?|\&/) this means
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>

answered Feb 13, 2016 at 20:28

Comments

5

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

answered Sep 16, 2016 at 6:19

Comments

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

answered Mar 24, 2017 at 6:47

Comments

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.

answered Mar 23, 2015 at 20:50

1 Comment

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.
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
10.3k13 gold badges82 silver badges121 bronze badges
answered Sep 19, 2018 at 16:14

1 Comment

Perfect Answer!
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;
}
answered Jun 23, 2016 at 10:07

Comments

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>

answered Oct 19, 2016 at 2:37

Comments

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++
answered Mar 6, 2015 at 17:15

Comments

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];
 }
})();
answered Jul 4, 2015 at 16:00

Comments

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"];
answered Feb 13, 2016 at 22:29

Comments

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'];
answered May 6, 2016 at 14:45

Comments

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]);
 }
 }
}
answered May 20, 2016 at 19:03

Comments

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
answered Jul 30, 2016 at 19:37

Comments

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"));
answered Mar 16, 2018 at 9:56

Comments

0

Using plain JavaScript and without regular expressions:

Object.fromEntries(new URL(url).searchParams);

The Object.fromEntries() static method transforms a list of key-value pairs into an object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

answered Feb 14, 2024 at 17:48

Comments

-1
$.urlParam = function(name) {
 var results = new RegExp('[\?&amp;]' + name + '=([^&amp;#]*)').exec(window.location.href);
 return results[1] || 0;
}
avpaderno
30k17 gold badges80 silver badges95 bronze badges
answered Nov 18, 2014 at 9:39

1 Comment

& is wrongly encoded as "&amp;" in above answer, refer to correct answer stackoverflow.com/a/25359264/73630
-1

use this

$.urlParam = function(name) {
 var results = new RegExp('[\?&amp;]' + name + '=([^&amp;#]*)').exec(window.location.href);
 return results[1] || 0;
}
answered Apr 24, 2015 at 9:16

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.