Is there a plugin-less way of retrieving query string values via jQuery (or without)?
If so, how? If not, is there a plugin which can do so?
Is there a plugin-less way of retrieving query string values via jQuery (or without)?
If so, how? If not, is there a plugin which can do so?
Update: Jan-2022
Using Proxy() is faster than using Object.fromEntries() and better supported
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "some_key" in eg "https://example.com/?some_key=some_value"
let value = params.some_key; // "some_value"
Update: June-2021
For a specific case when you need all query params:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
Update: Sep-2018
You can use URLSearchParams which is simple and has decent (but not complete) browser support.
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
Original
You don't need jQuery for that purpose. You can use just some pure JavaScript:
function getParameterByName(name, 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:
// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)
NOTE: If a parameter is present several times (?foo=lorem&foo=ipsum), you will get the first value (lorem). There is no standard about this and usages vary, see for example this question: Authoritative position of duplicate HTTP GET query keys.
NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, add 'i' modifier to RegExp
NOTE: If you're getting a no-useless-escape eslint error, you can replace name = name.replace(/[\[\]]/g, '\\$&'); with name = name.replace(/[[\]]/g, '\\$&').
This is an update based on the new URLSearchParams specs to achieve the same result more succinctly. See answer titled "URLSearchParams" below.
Roshambo on snipplr.com has a simple script to achieve this described in Get URL Parameters with jQuery | Improved. With his script you also easily get to pull out just the parameters you want.
Here's the gist:
$.urlParam = function(name, url) {
if (!url) {
url = window.location.href;
}
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
if (!results) {
return undefined;
}
return results[1] || undefined;
}
Then just get your parameters from the query string.
So if the URL/query string was xyz.example/index.html?lang=de.
Just call var langval = $.urlParam('lang');, and you've got it.
UZBEKJON has a great blog post on this as well, Get URL parameters & values with jQuery.
If you're using jQuery, you can use a library, such as jQuery BBQ: Back Button & Query Library.
...jQuery BBQ provides a full
.deparam()method, along with both hash state management, and fragment / query string parse and merge utility methods.
Edit: Adding Deparam Example:
var DeparamExample = function() {
var params = $.deparam.querystring();
//nameofparam is the name of a param from url
//code below will get param if ajax refresh with hash
if (typeof params.nameofparam == 'undefined') {
params = jQuery.deparam.fragment(window.location.href);
}
if (typeof params.nameofparam != 'undefined') {
var paramValue = params.nameofparam.toString();
}
};
If you want to just use plain JavaScript, you could use...
var getParamValue = (function() {
var params;
var resetParams = function() {
var query = window.location.search;
var regex = /[?&;](.+?)=([^&;]+)/g;
var match;
params = {};
if (query) {
while (match = regex.exec(query)) {
params[match[1]] = decodeURIComponent(match[2]);
}
}
};
window.addEventListener
&& window.addEventListener('popstate', resetParams);
resetParams();
return function(param) {
return params.hasOwnProperty(param) ? params[param] : null;
}
})();
Because of the new HTML History API and specifically history.pushState() and history.replaceState(), the URL can change which will invalidate the cache of parameters and their values.
This version will update its internal cache of parameters each time the history changes.
Roshambo jQuery method wasn't taking care of decode URL
http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/
Just added that capability also while adding in the return statement
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
Now you can find the updated gist:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
}
This is a function I created a while back and I'm quite happy with. It is not case sensitive - which is handy. Also, if the requested QS doesn't exist, it just returns an empty string.
I use a compressed version of this. I'm posting uncompressed for the novice types to better explain what's going on.
I'm sure this could be optimized or done differently to work faster, but it's always worked great for what I need.
Enjoy.
function getQSP(sName, sURL) {
var theItmToRtn = "";
var theSrchStrg = location.search;
if (sURL) theSrchStrg = sURL;
var sOrig = theSrchStrg;
theSrchStrg = theSrchStrg.toUpperCase();
sName = sName.toUpperCase();
theSrchStrg = theSrchStrg.replace("?", "&") theSrchStrg = theSrchStrg + "&";
var theSrchToken = "&" + sName + "=";
if (theSrchStrg.indexOf(theSrchToken) != -1) {
var theSrchTokenLth = theSrchToken.length;
var theSrchTokenLocStart = theSrchStrg.indexOf(theSrchToken) + theSrchTokenLth;
var theLocOfNextAndSign = theSrchStrg.indexOf("&", theSrchTokenLocStart);
theItmToRtn = unescape(sOrig.substring(theSrchTokenLocStart, theLocOfNextAndSign));
}
return unescape(theItmToRtn);
}
http://someurl.com?key=value&keynovalue&keyemptyvalue=&&keynovalue=nowhasvalue#somehash
?param=value)?param : no equal sign or value)?param= : equal sign, but no value to right of equal sign)?param=1¶m=2)?&& : no key or value)var queryString = window.location.search || '';
var keyValPairs = [];
var params = {};
queryString = queryString.substr(1);
if (queryString.length)
{
keyValPairs = queryString.split('&');
for (pairNum in keyValPairs)
{
var key = keyValPairs[pairNum].split('=')[0];
if (!key.length) continue;
if (typeof params[key] === 'undefined')
params[key] = [];
params[key].push(keyValPairs[pairNum].split('=')[1]);
}
}
params['key']; // returns an array of values (1..n)
key ["value"]
keyemptyvalue [""]
keynovalue [undefined, "nowhasvalue"]
If you have Underscore.js or lodash, a quick and dirty way to get this done is:
_.object(window.location.search.slice(1).split('&').map(function (val) { return val.split('='); }));