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?
See it in Action: https://codepen.io/ajorpheus/pen/XWyWWNQ
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)###Code:
-
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]);
}
}
###How to Call:
-
params['key']; // returns an array of values (1..n)
###Output:
-
key ["value"]
keyemptyvalue [""]
keynovalue [undefined, "nowhasvalue"]
This one works fine. Regular expressions in some of the other answers introduce unnecessary overhead.
function getQuerystring(key) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == key) {
return pair[1];
}
}
}
taken from here
decodeUriComponent
on the pair[1]
before you return it, if not replace pluses with spaces first as in all the other solutions here. Some of the other solutions also prefer a limit of 2 parts on the split =
to be more lenient in accepting input.
I developed a small library using techniques listed here to create an easy to use, drop-in solution to anyones troubles; It can be found here:
https://github.com/Nijikokun/query-js
Usage
Fetching specific parameter/key:
query.get('param');
Using the builder to fetch the entire object:
var storage = query.build();
console.log(storage.param);
and tons more... check the github link for more examples.
Features
#hello?page=3
user[]="jim"&user[]="bob"
&&
name&hello="world"
param=1¶m=2
4kb
One-liner to get the query:
var value = location.search.match(new RegExp(key + "=(.*?)($|\&)", "i"))[1];
(location.search.match(new RegExp('kiosk_modeasdf' + "=(.*?)($|\&)", "i")) || [])[1]
Commented
Jan 28, 2013 at 20:51
var value = location.search.match(new RegExp("hello" + "=(.*?)($|\&)", "i"))[1];
will return "world"
Here is my version of query string parsing code on GitHub.
It's "prefixed" with jquery.*, but the parsing function itself don't use jQuery. It's pretty fast, but still open for few simple performance optimizations.
Also it supports list & hash-tables encoding in the URL, like:
arr[]=10&arr[]=20&arr[]=100
or
hash[key1]=hello&hash[key2]=moto&a=How%20are%20you
jQuery.toQueryParams = function(str, separator) {
separator = separator || '&'
var obj = {}
if (str.length == 0)
return obj
var c = str.substr(0,1)
var s = c=='?' || c=='#' ? str.substr(1) : str;
var a = s.split(separator)
for (var i=0; i<a.length; i++) {
var p = a[i].indexOf('=')
if (p < 0) {
obj[a[i]] = ''
continue
}
var k = decodeURIComponent(a[i].substr(0,p)),
v = decodeURIComponent(a[i].substr(p+1))
var bps = k.indexOf('[')
if (bps < 0) {
obj[k] = v
continue;
}
var bpe = k.substr(bps+1).indexOf(']')
if (bpe < 0) {
obj[k] = v
continue;
}
var bpv = k.substr(bps+1, bps+bpe-1)
var k = k.substr(0,bps)
if (bpv.length <= 0) {
if (typeof(obj[k]) != 'object') obj[k] = []
obj[k].push(v)
} else {
if (typeof(obj[k]) != 'object') obj[k] = {}
obj[k][bpv] = v
}
}
return obj;
}
filters[topic][]=list
Commented
Sep 19, 2019 at 18:11
A very lightweight jQuery method:
var qs = window.location.search.replace('?','').split('&'),
request = {};
$.each(qs, function(i,v) {
var initial, pair = v.split('=');
if(initial = request[pair[0]]){
if(!$.isArray(initial)) {
request[pair[0]] = [initial]
}
request[pair[0]].push(pair[1]);
} else {
request[pair[0]] = pair[1];
}
return;
});
console.log(request);
And to alert, for example ?q
alert(request.q)
return
in your closure though, and I think you need to decodeUriComponent
the two pair[]
values as you read them.
I would rather use split()
instead of Regex for this operation:
function getUrlParams() {
var result = {};
var params = (window.location.search.split('?')[1] || '').split('&');
for(var param in params) {
if (params.hasOwnProperty(param)) {
var paramParts = params[param].split('=');
result[paramParts[0]] = decodeURIComponent(paramParts[1] || "");
}
}
return result;
}
Here's what I'm using:
/**
* Examples:
* getUrlParams()['myparam'] // url defaults to the current page
* getUrlParams(url)['myparam'] // url can be just a query string
*
* Results of calling `getUrlParams(url)['myparam']` with various urls:
* example.com (undefined)
* example.com? (undefined)
* example.com?myparam (empty string)
* example.com?myparam= (empty string)
* example.com?myparam=0 (the string '0')
* example.com?myparam=0&myparam=override (the string 'override')
*
* Origin: http://stackoverflow.com/a/23946023/2407309
*/
function getUrlParams (url) {
var urlParams = {} // return value
var queryString = getQueryString()
if (queryString) {
var keyValuePairs = queryString.split('&')
for (var i = 0; i < keyValuePairs.length; i++) {
var keyValuePair = keyValuePairs[i].split('=')
var paramName = keyValuePair[0]
var paramValue = keyValuePair[1] || ''
urlParams[paramName] = decodeURIComponent(paramValue.replace(/\+/g, ' '))
}
}
return urlParams // functions below
function getQueryString () {
var reducedUrl = url || window.location.search
reducedUrl = reducedUrl.split('#')[0] // Discard fragment identifier.
var queryString = reducedUrl.split('?')[1]
if (!queryString) {
if (reducedUrl.search('=') !== false) { // URL is a query string.
queryString = reducedUrl
}
}
return queryString
} // getQueryString
} // getUrlParams
Returning 'override' rather than '0' in the last case makes it consistent with PHP. Works in IE7.
paramName
needs to be decodeURIComponent
ed too technically, though I doubt anyone would use non-trivial params.)
defensive semicolon
.
Commented
Apr 1, 2015 at 12:04
For those who wants a short method (with limitations):
location.search.split('myParameter=')[1]
Get all querystring parameters including checkbox values (arrays).
Considering the correct & normal use of GET parameters, the things I see it's missing, on most functions, is the support for arrays and removing the hash data.
So I wrote this function:
function qs(a){
if(!a)return {};
a=a.split('#')[0].split('&');
var b=a.length,c={},d,k,v;
while(b--){
d=a[b].split('=');
k=d[0].replace('[]',''),v=decodeURIComponent(d[1]||'');
c[k]?typeof c[k]==='string'?(c[k]=[v,c[k]]):(c[k].unshift(v)):c[k]=v;
}
return c
}
Using shorthand operators & while-- loop, the performance should be very good to.
Support:
Notes:
It does not support object arrays (key[key]=value)
If the space is + it remains a +.
Add .replace(/\+/g, " ")
if you need.
Usage:
qs('array[]=1&array[]=2&key=value&empty=&empty2#hash')
Return:
{
"empty": "",
"key": "value",
"array": [
"1",
"2"
]
}
Demo:
Info
If you don't understand something or you can't read the function just ask. I'm happy to explain what I did here.
If you think the function is unreadable and unmaintainable I'm happy to rewrite the function for you, but consider that shorthand & bitwise operators are always faster than a standard syntax (maybe read about shorthands and bitwise operators in the ECMA-262 book or use your favorite search engine). Rewriting the code in a standard readable syntax means performance loss.
location.search
which doesn't contain it. I'm also not clear what you mean "bitwise operators" - you're using empty-or-undefined-is-false in a couple of places which is as close as you get but there's no bit manipulation here.
function getUrlVar(key){
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && unescape(result[1]) || "";
}
The following code will create an object which has two methods:
isKeyExist
: Check if a particular parameter existgetValue
: Get the value of a particular parameter.
var QSParam = new function() {
var qsParm = {};
var query = window.location.search.substring(1);
var params = query.split('&');
for (var i = 0; i < params.length; i++) {
var pos = params[i].indexOf('=');
if (pos > 0) {
var key = params[i].substring(0, pos);
var val = params[i].substring(pos + 1);
qsParm[key] = val;
}
}
this.isKeyExist = function(query){
if(qsParm[query]){
return true;
}
else{
return false;
}
};
this.getValue = function(query){
if(qsParm[query])
{
return qsParm[query];
}
throw "URL does not contain query "+ query;
}
};
Try this:
String.prototype.getValueByKey = function(k){
var p = new RegExp('\\b'+k+'\\b','gi');
return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p)+k.length+1).substr(0,this.substr(this.search(p)+k.length+1).search(/(&|;|$)/))) : "";
};
Then call it like so:
if(location.search != "") location.search.getValueByKey("id");
You can use this for cookies also:
if(navigator.cookieEnabled) document.cookie.getValueByKey("username");
This only works for strings that have key=value[&|;|$]
... will not work on objects/arrays.
If you don't want to use String.prototype... move it to a function and pass the string as an argument
Here's my own take on this. This first function decodes a URL string into an object of name/value pairs:
url_args_decode = function (url) {
var args_enc, el, i, nameval, ret;
ret = {};
// use the DOM to parse the URL via an 'a' element
el = document.createElement("a");
el.href = url;
// strip off initial ? on search and split
args_enc = el.search.substring(1).split('&');
for (i = 0; i < args_enc.length; i++) {
// convert + into space, split on =, and then decode
args_enc[i].replace(/\+/g, ' ');
nameval = args_enc[i].split('=', 2);
ret[decodeURIComponent(nameval[0])]=decodeURIComponent(nameval[1]);
}
return ret;
};
And as an added bonus, if you change some of the args, you can use this second function to put the array of args back into the URL string:
url_args_replace = function (url, args) {
var args_enc, el, name;
// use the DOM to parse the URL via an 'a' element
el = document.createElement("a");
el.href = url;
args_enc = [];
// encode args to go into url
for (name in args) {
if (args.hasOwnProperty(name)) {
name = encodeURIComponent(name);
args[name] = encodeURIComponent(args[name]);
args_enc.push(name + '=' + args[name]);
}
}
if (args_enc.length > 0) {
el.search = '?' + args_enc.join('&');
} else {
el.search = '';
}
return el.href;
};
url_args_replace
) can be used via $.param()
Commented
Aug 28, 2012 at 13:51
I used this code (JavaScript) to get the what is passed through the URL:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
Then to assign the value to a variable, you only have to specify which parameter you want to get, ie if the URL is example.com/?I=1&p=2&f=3
You can do this to get the values:
var getI = getUrlVars()["I"];
var getP = getUrlVars()["p"];
var getF = getUrlVars()["f"];
then the values would be:
getI = 1, getP = 2 and getF = 3
decodeURIComponent
on the key and the value and you probably don't need the i
flag on the regexp (not that that really matters).
The following function returns an object version of your queryString.
You can simply write obj.key1
and obj.key2
to access values of key1
and key2
in parameter.
function getQueryStringObject()
{
var querystring = document.location.search.replace('?','').split( '&' );
var objQueryString={};
var key="",val="";
if(typeof querystring == 'undefined')
{
return (typeof querystring);
}
for(i=0;i<querystring.length;i++)
{
key=querystring[i].split("=")[0];
val=querystring[i].split("=")[1];
objQueryString[key] = val;
}
return objQueryString;
}
And to use this function you can write
var obj= getQueryStringObject();
alert(obj.key1);
This function converts the querystring to a JSON-like object, it also handles value-less and multi-value parameters:
"use strict";
function getQuerystringData(name) {
var data = { };
var parameters = window.location.search.substring(1).split("&");
for (var i = 0, j = parameters.length; i < j; i++) {
var parameter = parameters[i].split("=");
var parameterName = decodeURIComponent(parameter[0]);
var parameterValue = typeof parameter[1] === "undefined" ? parameter[1] : decodeURIComponent(parameter[1]);
var dataType = typeof data[parameterName];
if (dataType === "undefined") {
data[parameterName] = parameterValue;
} else if (dataType === "array") {
data[parameterName].push(parameterValue);
} else {
data[parameterName] = [data[parameterName]];
data[parameterName].push(parameterValue);
}
}
return typeof name === "string" ? data[name] : data;
}
We perform a check for undefined
on parameter[1]
because decodeURIComponent
returns the string "undefined" if the variable is undefined
, and that's wrong.
Usage:
"use strict";
var data = getQuerystringData();
var parameterValue = getQuerystringData("parameterName");
I did a small URL library for my needs here: https://github.com/Mikhus/jsurl
It's a more common way of manipulating the URLs in JavaScript. Meanwhile it's really lightweight (minified and gzipped < 1 KB) and has a very simple and clean API. And it does not need any other library to work.
Regarding the initial question, it's very simple to do:
var u = new Url; // Current document URL
// or
var u = new Url('http://user:[email protected]:8080/some/path?foo=bar&bar=baz#anchor');
// Looking for query string parameters
alert( u.query.bar);
alert( u.query.foo);
// Modifying query string parameters
u.query.foo = 'bla';
u.query.woo = ['hi', 'hey']
alert(u.query.foo);
alert(u.query.woo);
alert(u);
filters[topic][]=list
Commented
Sep 19, 2019 at 18:19
I took this answer and added support for optionally passing the URL in as a parameter; falls back to window.location.search. Obviously this is useful for getting the query string parameters from URLs that are not the current page:
(function($, undef) {
$.QueryString = function(url) {
var pairs, qs = null, index, map = {};
if(url == undef){
qs = window.location.search.substr(1);
}else{
index = url.indexOf('?');
if(index == -1) return {};
qs = url.substring(index+1);
}
pairs = qs.split('&');
if (pairs == "") return {};
for (var i = 0; i < pairs.length; ++i)
{
var p = pairs[i].split('=');
if(p.length != 2) continue;
map[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return map;
};
})(jQuery);
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('='); }));
_.chain(document.location.search.slice(1).split('&')).invoke('split', '=').object().value()
Commented
Jan 7, 2014 at 14:46
There is a nice little url
utility for this with some cool sugaring:
http://www.example.com/path/index.html?silly=willy#chucky=cheese
url(); // http://www.example.com/path/index.html?silly=willy#chucky=cheese
url('domain'); // example.com
url('1'); // path
url('-1'); // index.html
url('?'); // silly=willy
url('?silly'); // willy
url('?poo'); // (an empty string)
url('#'); // chucky=cheese
url('#chucky'); // cheese
url('#poo'); // (an empty string)
Check out more examples and download here: https://github.com/websanova/js-url#url
This the most simple and small function JavaScript to get int ans String parameter value from URL
/* THIS FUNCTION IS TO FETCH INT PARAMETER VALUES */
function getParameterint(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n);
}
getParameteraint("page");
getParameteraint("pagee");
/*THIS FUNCTION IS TO FETCH STRING PARAMETER*/
function getParameterstr(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=url.replace(param+"=","");
alert(n);
}
getParameterstr("str");
Source And DEMO : http://bloggerplugnplay.blogspot.in/2012/08/how-to-get-url-parameter-in-javascript.html
?xyz=page&str=Expected&page=123
won't return 123 because it picks up the page
string from xyz=page
, and str
will return Expected&page=123
rather than just Expected
if it's not the last value on the line, etc. You're also not decodeUriComponent-ing the values extracted. Plus I couldn't try your demo - I got redirected to a betting website??
I believe this to be an accurate and concise way to achieve this (modified from http://css-tricks.com/snippets/javascript/get-url-variables/):
function getQueryVariable(variable) {
var query = window.location.search.substring(1), // Remove the ? from the query string.
vars = query.split("&"); // Split all values by ampersand.
for (var i = 0; i < vars.length; i++) { // Loop through them...
var pair = vars[i].split("="); // Split the name from the value.
if (pair[0] == variable) { // Once the requested value is found...
return ( pair[1] == undefined ) ? null : pair[1]; // Return null if there is no value (no equals sign), otherwise return the value.
}
}
return undefined; // Wasn't found.
}
There's a robust implementation in Node.js's source
https://github.com/joyent/node/blob/master/lib/querystring.js
Also TJ's qs does nested params parsing
https://github.com/visionmedia/node-querystring
var getUrlParameters = function (name, url) {
if (!name) {
return undefined;
}
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
url = url || location.search;
var regex = new RegExp('[\\?&#]' + name + '=?([^&#]*)', 'gi'), result, resultList = [];
while (result = regex.exec(url)) {
resultList.push(decodeURIComponent(result[1].replace(/\+/g, ' ')));
}
return resultList.length ? resultList.length === 1 ? resultList[0] : resultList : undefined;
};
There are many solutions to retrieve URI query values, I prefer this one because it's short and works great:
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
encodeURIComponent
for the key name is new, though, and on one hand more correct than the accepted answer for considering encodings in the key but on the other will still miss non-minimal encodings, e.g. get("key")
won't match ?k%65y=value
.
A simple solution with plain JavaScript and regular expressions:
alert(getQueryString("p2"));
function getQueryString (Param) {
return decodeURI("http://www.example.com/?p1=p11&p2=p2222".replace(new RegExp("^(?:.*[&?]" + encodeURI(Param).replace(/[.+*]/g, "$&") + "(?:=([^&]*))?)?.*$", "i"), "$1"));
}
If you want array-style parameters URL.js supports arbitrarily nested array-style parameters as well as string indexes (maps). It also handles URL decoding.
url.get("val[0]=zero&val[1]=one&val[2]&val[3]=&val[4]=four&val[5][0]=n1&val[5][1]=n2&val[5][2]=n3&key=val", {array:true});
// Result
{
val: [
'zero',
'one',
true,
'',
'four',
[ 'n1', 'n2', 'n3' ]
]
key: 'val'
}
If you do not wish to use a JavaScript library you can use the JavaScript string functions to parse window.location
. Keep this code in an external .js file and you can use it over and over again in different projects.
// Example - window.location = "index.htm?name=bob";
var value = getParameterValue("name");
alert("name = " + value);
function getParameterValue(param)
{
var url = window.location;
var parts = url.split('?');
var params = parts[1].split('&');
var val = "";
for ( var i=0; i<params.length; i++)
{
var paramNameVal = params[i].split('=');
if ( paramNameVal[0] == param )
{
val = paramNameVal[1];
}
}
return val;
}
This is very simple method to get parameter value(query string)
Use gV(para_name)
function to retrieve its value
var a=window.location.search;
a=a.replace(a.charAt(0),""); //Removes '?'
a=a.split("&");
function gV(x){
for(i=0;i<a.length;i++){
var b=a[i].substr(0,a[i].indexOf("="));
if(x==b){
return a[i].substr(a[i].indexOf("=")+1,a[i].length)}