Get query string parameters url values with jQuery / Javascript (querystring)
Solution 1
After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!
//Assuming URL has "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?
post=1234&action=edit&active=1"
UPDATE : IE is not supported
use this function from an answer below instead of URLSearchParams
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('action')); //edit
Solution 2
Why extend jQuery? What would be the benefit of extending jQuery vs just having a global function?
function qs(key) {
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}
http://jsfiddle.net/gilly3/sgxcL/
An alternative approach would be to parse the entire query string and store the values in an object for later use. This approach doesn't require a regular expression and extends the window.location
object (but, could just as easily use a global variable):
location.queryString = {};
location.search.substr(1).split("&").forEach(function (pair) {
if (pair === "") return;
var parts = pair.split("=");
location.queryString[parts[0]] = parts[1] &&
decodeURIComponent(parts[1].replace(/\+/g, " "));
});
http://jsfiddle.net/gilly3/YnCeu/
This version also makes use of Array.forEach()
, which is unavailable natively in IE7 and IE8. It can be added by using the implementation at MDN, or you can use jQuery's $.each()
instead.
Solution 3
JQuery jQuery-URL-Parser plugin do the same job, for example to retrieve the value of search query string param, you can use
$.url().param('search');
This library is not actively maintained. As suggested by the author of the same plugin, you can use URI.js.
Or you can use js-url instead. Its quite similar to the one below.
So you can access the query param like $.url('?search')
Solution 4
Found this gem from our friends over at SitePoint. https://www.sitepoint.com/url-parameters-jquery/.
Using PURE jQuery. I just used this and it worked. Tweaked it a bit for example sake.
//URL is http://www.example.com/mypage?ref=registration&[email protected]
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('ref')); //registration
console.log($.urlParam('email')); //[email protected]
Use as you will.
Solution 5
This isn't my code sample, but I've used it in the past.
//First Add this to extend jQuery
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
//Second call with this:
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its name
var byName = $.getUrlVar('name');
Related videos on Youtube
TroySteven
PHP, C#, JavaScript, Classic ASP, and ASP.NET. His database experience includes both SQL Server and MySQL.
Updated on October 09, 2021Comments
-
TroySteven over 2 years
Anyone know of a good way to write a jQuery extension to handle query string parameters? I basically want to extend the jQuery magic
($)
function so I can do something like this:$('?search').val();
Which would give me the value "test" in the following URL:
http://www.example.com/index.php?search=test
.I've seen a lot of functions that can do this in jQuery and Javascript, but I actually want to extend jQuery to work exactly as it is shown above. I'm not looking for a jQuery plugin, I'm looking for an extension to the jQuery method.
-
Nico Westerdale over 12 yearsAsked and answered: stackoverflow.com/questions/901115/…
-
mrtsherman over 12 years@NicoWesterdale - I went through that link, but didn't see any answers that solve this particular question. He said he wants exactly as above.
-
Andrew over 12 yearsI don't think you can do this, a string passed in gets parsed by sizzler, then resolved to an array of DOM objects. You can extend the matcher to provide custom filters, but you can't have a jquery object based on a string.
-
Quentin over 12 yearsIsn't
$
overloaded enough? -
Nico Westerdale over 12 years@mrtsherman Look at the getParameterByName() function in the link I provided. No you can't do it from directly within a $ prompt, but that's not what jQuery selectors are for. He's just selecting part of a URL string, not trying to access part of the DOM which is what $() does. It's a totally different thing. If you really wanted to use jQuery you could write a plugin that used this syntax: $.getParameterByName(param), there's an example further down on that page I linked to that does exactly that. Kinda pointless though.
-
-
Muhd over 12 yearsIt's not common but it is valid to use semi-colons instead of ampersands in the query parameters.
-
Muhd over 12 yearsNice. And the code is in the public domain so you don't even have to include the comments.
-
gilly3 over 12 years@Muhd - It's "valid" to use any delimiter you like in a querystring as long as your code understands it. But, when a form is submitted, the form fields are submitted as
name=value
pairs, separated by&
. If your code is using a custom querystring format, obviously, you'll need to write a custom querystring parser wherever the querystring is consumed, whether on the server or the client. -
nick almost 12 yearsThe W3C recommendation is to use semi-colon delimiters, see w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.2.2
-
gilly3 almost 12 years@nick - Interesting. But their suggestion for HTTP servers to treat semi-colons as ampersands only serves to make HTML prettier when using a link to mimic a form submission. It is just a suggestion and is non-standard. A standard form
GET
submission is encoded asapplication/x-www-form-urlencoded
, with values separated by&
. My code handles that standard. Custom url structures such as the one you linked will need a custom parser server-side and client-side. Regardless, adding such capability to my code above would be trivial. -
nick almost 12 years@gilly indeed - if you want portable code you need to support both
-
mplungjan over 10 yearsIf your name has no junk, you can drop the first regex and it make more sense to start from location.search
-
kampsj over 10 yearsGood solution but won't work if you happen to be testing via file://
-
RameshVel over 10 yearsWhats that have to do anything with, @kampsj
-
Jess almost 10 yearsHi @kampsj, testing with
file://
protocol will cause a lot more stuff not to work. You can create a very quick and easy static HTML server with node.js. stackoverflow.com/questions/16333790/… -
Kalidasan over 8 yearsWhy we need plugin for very small task?
-
RameshVel over 8 yearsIts based on the needs, if you are pereforming more than just retrieving a field from URL.. So if you dont want to use a plugin, then checkout the answers below, there are lot of alternatives
-
bhtabor over 7 yearsGreat. Thanks! I don't think you need the last closing brace tag though.
-
ClosDesign over 7 yearsAhh yes, you are correct. Edited the post. That was left over from some if statement in my code. Thanks.
-
BrainSlugs83 over 7 yearsYou shouldn't split on '=', it's technically okay to have a second equals sign in the value of any key/value pair. -- Only the first equals sign you encounter (per key/value pair) should be treated as a delimiter. (Also, the equals sign isn't strictly required; it's possible to have a key with no value.)
-
BrainSlugs83 over 7 yearsYou should use window.location.search instead of .href -- otherwise, good.
-
Admin about 7 yearsI haven't seen any erroring using this code. What browser are you using? I've tested it against current Firefox, Chrome, and Safari.
-
Jerinaw about 7 yearsYeah sorry I read it wrong. I thought I saw it call a method on something that was returning undefined. So really it's just running once when it doesn't have to. When search is
""
. And you get {"": "undefined"} -
Admin about 7 yearsYeah. That could probably use some refining.
-
master_dodo almost 7 yearsInstead of
results[1] || 0
, you must do if (results) {return results[1]} return 0; bcoz query parameters may not be present at all. And modifying will handle all generic cases. -
JanErikGunnar over 6 yearsThis plugin is no longer maintained and the author itself is suggesting to use other plugins instead.
-
RameshVel over 6 yearsthanks @JanErikGunnar, Please check the updated answer
-
Yovav over 6 yearsAdd "i" to the RegExp() so the key can be case insensitive: new RegExp("[?&]"+key+"=([^&]+)(&|$)", "i"));
-
divine over 6 yearsis URLSearchParams supported by all browsers?
-
Saurin over 6 yearsOops! ohh man, IE is not supported !! I have just tested on it. While Chrome, FF, Safari has no issue.
-
M.Babcock over 6 years@RameshVel Did you intend for both URI.js and js-url links to point to the same location? Maybe you meant js-url to point here?
-
RameshVel over 6 years@M.Babcock yep the link was wrong. fixed now. thank you
-
Shane Rowatt about 6 yearsThe return statement should be
return (results && results[1]) || 0;
-
dnns about 6 yearsIf the param is not set, it'll return
null
, and cause an error. I modified it to:return (results !== null) ? results[1] || 0 : false;
to solve the issue. This way it'll returnfalse
if the param is not set. Thanks for the solution. -
Volomike about 5 yearsWhat do you do if you have something like
https://example.com/?c=Order+ID
? That plus sign still remains on this function. -
Volomike about 5 yearsThis properly handled where a query param contained a plus (+) sign, while other examples did not.
-
Yogi about 5 years@divine - There is a polyfill for URLSearchParams here: github.com/WebReflection/url-search-params
-
Code-Apprentice about 5 years"Using PURE jQuery." This solution doesn't actually use any JQuery. It only extends JQuery with what could just as easily be a stand alone function.
-
Carter Medlin almost 5 yearsTo get rid of the plus sign and decode use
decodeURIComponent($.urlParam('email').replace(/\+/g," "));
-
JF Gagnon over 4 yearsClean solution. Worked perfectly in my case.
-
Mupinc about 4 years$.extend({ getUrlVars: function(){ var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); var k = hash.shift(); vars.push(k); vars[k] = hash.join(""); } return vars; }, getUrlVar: function(name){ return $.getUrlVars()[name]; } });
-
Louisvdw about 4 yearsIf you add a polyfill for unsupported browsers this URLSearchParams solution works well. github.com/ungap/url-search-params
-
Toskan almost 4 yearswont work with say
https://mytest.com/bippo/#/?utm_source=teeest
orhttps://mytest.com/bippo/#/url/?utm_source=teeest
-
Toskan almost 4 yearsdont understand the jsfiddle. Will this work for example with:
https://mytest.com/bippo/#/url/?utm_source=teeest
-
Toskan almost 4 yearswont work with
https://mytest.com/bippo/#/url/?utm_source=teeest
-
gilly3 over 3 years@Toskan - You can adapt it to work. I assume you want to treat the
?utm_source=teeest
portion as the querystring. Since that portion in your URL comes after the#
, it's not part of the traditional querystring, and thus not available inlocation.search
, which both of my examples rely on. You can modify myqs
function to uselocation.hash
instead oflocation.search
and it will work. -
farialima over 2 yearsThe solution is not complete, il should call
decodeURIComponent
, and replace+
with space... see previous solution