如何在JavaScript中获取查询字符串值?
是否有无插件的方式通过jQuery(或不通过jQuery)检索值如何在JavaScript中获取查询字符串值?,javascript,url,plugins,query-string,Javascript,Url,Plugins,Query String,是否有无插件的方式通过jQuery(或不通过jQuery)检索值 如果是,怎么做?如果没有,是否有插件可以这样做?如果使用jQuery,可以使用库,例如 …jQuery BBQ提供了一个完整的.deparam()方法,以及哈希状态管理、片段/查询字符串解析和合并实用程序方法 编辑:添加Deparam示例: var DeparamExample=function(){ var params=$.deparam.querystring(); //nameofparam是url中参数的名称 //如果
如果是,怎么做?如果没有,是否有插件可以这样做?如果使用jQuery,可以使用库,例如 …jQuery BBQ提供了一个完整的
.deparam()
方法,以及哈希状态管理、片段/查询字符串解析和合并实用程序方法
编辑:添加Deparam示例:
var DeparamExample=function(){
var params=$.deparam.querystring();
//nameofparam是url中参数的名称
//如果ajax使用哈希刷新,下面的代码将获得param
if(typeof params.nameofparam==“未定义”){
params=jQuery.deparam.fragment(window.location.href);
}
if(typeof params.nameofparam!=“未定义”){
var paramValue=params.nameofparam.toString();
}
};代码>更新:2021年6月
对于需要所有查询参数的特定情况:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
更新日期:2018年9月
你可以用一个简单又有吸引力的方法
原创
您不需要jQuery来实现这一目的。您可以只使用一些纯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, ' '));
}
用法:
// 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)
getQueryStringKey = function(key) {
return getQueryStringAsObject()[key];
};
getQueryStringAsObject = function() {
var b, cv, e, k, ma, sk, v, r = {},
d = function (v) { return decodeURIComponent(v).replace(/\+/g, " "); }, //# d(ecode) the v(alue)
q = window.location.search.substring(1), //# suggested: q = decodeURIComponent(window.location.search.substring(1)),
s = /([^&;=]+)=?([^&;]*)/g //# original regex that does not allow for ; as a delimiter: /([^&=]+)=?([^&]*)/g
;
//# ma(make array) out of the v(alue)
ma = function(v) {
//# If the passed v(alue) hasn't been setup as an object
if (typeof v != "object") {
//# Grab the cv(current value) then setup the v(alue) as an object
cv = v;
v = {};
v.length = 0;
//# If there was a cv(current value), .push it into the new v(alue)'s array
//# NOTE: This may or may not be 100% logical to do... but it's better than loosing the original value
if (cv) { Array.prototype.push.call(v, cv); }
}
return v;
};
//# While we still have key-value e(ntries) from the q(uerystring) via the s(earch regex)...
while (e = s.exec(q)) { //# while((e = s.exec(q)) !== null) {
//# Collect the open b(racket) location (if any) then set the d(ecoded) v(alue) from the above split key-value e(ntry)
b = e[1].indexOf("[");
v = d(e[2]);
//# As long as this is NOT a hash[]-style key-value e(ntry)
if (b < 0) { //# b == "-1"
//# d(ecode) the simple k(ey)
k = d(e[1]);
//# If the k(ey) already exists
if (r[k]) {
//# ma(make array) out of the k(ey) then .push the v(alue) into the k(ey)'s array in the r(eturn value)
r[k] = ma(r[k]);
Array.prototype.push.call(r[k], v);
}
//# Else this is a new k(ey), so just add the k(ey)/v(alue) into the r(eturn value)
else {
r[k] = v;
}
}
//# Else we've got ourselves a hash[]-style key-value e(ntry)
else {
//# Collect the d(ecoded) k(ey) and the d(ecoded) sk(sub-key) based on the b(racket) locations
k = d(e[1].slice(0, b));
sk = d(e[1].slice(b + 1, e[1].indexOf("]", b)));
//# ma(make array) out of the k(ey)
r[k] = ma(r[k]);
//# If we have a sk(sub-key), plug the v(alue) into it
if (sk) { r[k][sk] = v; }
//# Else .push the v(alue) into the k(ey)'s array
else { Array.prototype.push.call(r[k], v); }
}
}
//# Return the r(eturn value)
return r;
};
注意:如果一个参数多次出现(?foo=lorem&foo=ipsum
),您将获得第一个值(lorem
)。这方面没有标准,用法也各不相同,例如,请参见以下问题:
注意:该函数区分大小写。如果您更喜欢不区分大小写的参数名
这是一个基于新的更新,以更简洁地实现相同的结果。请参阅下面标题为“”的答案。snipplr.com上的Roshambo有一个简单的脚本来实现中所述的功能。使用他的脚本,您还可以轻松地提取所需的参数
要点如下:
$.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;
}
然后从查询字符串中获取参数
因此,如果URL/查询字符串是xyz.com/index.html?lang=de
只需调用var langval=$.urlParam('lang')代码>,您就知道了
UZBEKJON也在这方面发表了一篇很好的博客文章。这里发布的一些解决方案效率低下。每次脚本需要访问参数时都重复正则表达式搜索是完全不必要的,只需一个函数就可以将参数拆分为关联数组样式的对象。如果您没有使用HTML5历史API,则每次加载页面只需要一次。这里的其他建议也无法正确解码URL
var urlParams;
(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);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
在处理数组样式的查询字符串时,也可以很容易地对其进行改进。这方面的一个例子是,但是由于数组样式参数没有在中定义,所以我不会用源代码污染这个答案
此外,正如评论中指出的,
是key=value
对的合法分隔符。它需要一个更复杂的正则表达式来处理
或&
,我认为这是不必要的,因为很少使用了code>,我想说的是,两者都使用的可能性更大。如果您需要支持
而不是&
,只需在正则表达式中交换它们
如果您使用的是服务器端预处理语言,那么您可能希望使用其本机JSON函数来完成繁重的工作。例如,在PHP中,您可以编写:
<script>var urlParams = <?php echo json_encode($_GET, JSON_HEX_TAG);?>;</script>
因此,这就是管理it的方法:
let urlParams = {};
(window.onpopstate = function () {
let 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);
while (match = search.exec(query)) {
if (decode(match[1]) in urlParams) {
if (!Array.isArray(urlParams[decode(match[1])])) {
urlParams[decode(match[1])] = [urlParams[decode(match[1])]];
}
urlParams[decode(match[1])].push(decode(match[2]));
} else {
urlParams[decode(match[1])] = decode(match[2]);
}
}
})();
函数GET(){
var数据=[];
对于(x=0;x
ES2015(ES6)
没有jQuery
谷歌方法
撕开谷歌的代码,我找到了他们使用的方法:getUrlParameters
function (b) {
var c = typeof b === "undefined";
if (a !== h && c) return a;
for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {
var l = b[f][p]("=");
if (l !== -1) {
var q = b[f][I](0, l),
l = b[f][I](l + 1),
l = l[Ca](/\+/g, " ");
try {
d[q] = e(l)
} catch (A) {}
}
}
c && (a = d);
return d
}
用法
()
准备代码:方法声明
拆分测试代码
正则表达式测试代码
在Windows Server 2008 R2/7 x64上测试Firefox 4.0 x86
- 分割法:144780±2.17%
- 正则表达式方法:13891±0.85%| 90%较慢
我尝试将Andy E的优秀解决方案变成一个成熟的jQuery插件:
;(function ($) {
$.extend({
getQueryString: function (name) {
function parseParams() {
var params = {},
e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
params[d(e[1])] = d(e[2]);
return params;
}
if (!this.queryStringParams)
this.queryStringParams = parseParams();
return this.queryStringParams[name];
}
});
})(jQuery);
语法是:
var someVar = $.getQueryString('myParam');
两全其美 高尔夫代码:
var a = location.search&&location.search.substr(1).replace(/\+/gi," ").split("&");
for (var i in a) {
var s = a[i].split("=");
a[i] = a[unescape(s[0])] = unescape(s[1]);
}
展示它
for (i in a) {
document.write(i + ":" + a[i] + "<br/>");
};
Roshambo jQuery方法不负责解码URL
在添加return语句时也添加了该功能
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
现在您可以找到更新的要点:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
}
这是我不久前创建的一个函数,我非常满意。它不区分大小写,这很方便。此外,如果请求的QS不存在,它只返回一个空字符串
我使用这个的压缩版本。我为新手类型发布了未压缩的帖子,以便更好地解释发生了什么
我相信这可以被优化或做不同的工作更快,但它总是为我需要的伟大工作
享受
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);
}
改进版:
有关改进的更多信息,请参见:我经常使用正则表达式,但不是为了这个
在我的应用程序中读取一次查询字符串,并从所有键/值对构建一个对象,对我来说似乎更容易、更高效,如:
var search = function() {
var s = window.location.search.substr(1),
p = s.split(/\&/), l = p.length, kv, r = {};
if (l === 0) {return false;}
while (l--) {
kv = p[l].split(/\=/);
r[kv[0]] = decodeURIComponent(kv[1] || '') || true;
}
return r;
}();
对于类似http://domain.com?param1=val1¶m2=val2
您可以稍后在代码中获取它们的值,如search.param1
和search.param2
只是另一个建议。该插件允许检索URL的所有部分,包括锚、主机等
它可以与jQuery一起使用,也可以不与jQuery一起使用
用法非常简单和酷:
var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value'); // jQuery version
var url = purl('http://allmarkedup.com/folder/dir/index.html?item=value'); // plain JS version
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
然而,截至2014年11月11日,Purl不再维持
;(function ($) {
$.extend({
getQueryString: function (name) {
function parseParams() {
var params = {},
e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
params[d(e[1])] = d(e[2]);
return params;
}
if (!this.queryStringParams)
this.queryStringParams = parseParams();
return this.queryStringParams[name];
}
});
})(jQuery);
var someVar = $.getQueryString('myParam');
var a = location.search&&location.search.substr(1).replace(/\+/gi," ").split("&");
for (var i in a) {
var s = a[i].split("=");
a[i] = a[unescape(s[0])] = unescape(s[1]);
}
for (i in a) {
document.write(i + ":" + a[i] + "<br/>");
};
0:can
1:cheezburger
i:can
has:cheezburger
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
}
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);
}
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var search = function() {
var s = window.location.search.substr(1),
p = s.split(/\&/), l = p.length, kv, r = {};
if (l === 0) {return false;}
while (l--) {
kv = p[l].split(/\=/);
r[kv[0]] = decodeURIComponent(kv[1] || '') || true;
}
return r;
}();
var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value'); // jQuery version
var url = purl('http://allmarkedup.com/folder/dir/index.html?item=value'); // plain JS version
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
var url = new URI('http://allmarkedup.com/folder/dir/index.html?item=value'); // plain JS version
url.protocol(); // returns 'http'
url.path(); // returns '/folder/dir/index.html'
var url = 'http://sb.com/reg/step1?param';
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i) {
var p=a[i].split('=', 2);
if (p[1]) p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
b[p[0]] = p[1];
}
return b;
})((url.split('?'))[1].split('&'));
if (!window.location.getParameter ) {
window.location.getParameter = function(key) {
function parseParams() {
var params = {},
e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
params[d(e[1])] = d(e[2]);
return params;
}
if (!this.queryStringParams)
this.queryStringParams = parseParams();
return this.queryStringParams[key];
};
}
function qs(key) {
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[key];
}
var result = qs('someKey');
var data = URI('?foo=bar&bar=baz&foo=world').query(true);
data == {
"foo": ["bar", "world"],
"bar": "baz"
}
// get an array with all querystring values
// example: var valor = getUrlVars()["valor"];
function getUrlVars() {
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;
}
const params = new URLSearchParams(location.search);
const params = (new URL(location)).searchParams;
const url = new URL('https://example.com?foo=1&bar=2');
const params = new URLSearchParams(url.search);
const params = new URL('https://example.com?foo=1&bar=2').searchParams;
params.get('foo'); // "1"
params.get('bar'); // "2"
function get_query(){
var url = location.search;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
var $_GET = get_query();
{
x: "6",
y: undefined,
z: "hello"
}
function get(n) {
var half = location.search.split(n + '=')[1];
return half !== undefined ? decodeURIComponent(half.split('&')[0]) : null;
}
function get(n) {
var half = location.search.split('&' + n + '=')[1];
if (!half) half = location.search.split('?' + n + '=')[1];
return half !== undefined ? decodeURIComponent(half.split('&')[0]) : null;
}
function getQueryStringValueByName(name) {
var queryStringFromStartOfValue = location.search.split(name + '=')[1];
return queryStringFromStartOfValue !== undefined ? queryStringFromStartOfValue.split('&')[0] : null;
URLParser(url).getParam('myparam1')
var url = "http://www.test.com/folder/mypage.html?myparam1=1&myparam2=2#something";
function URLParser(u){
var path="",query="",hash="",params;
if(u.indexOf("#") > 0){
hash = u.substr(u.indexOf("#") + 1);
u = u.substr(0 , u.indexOf("#"));
}
if(u.indexOf("?") > 0){
path = u.substr(0 , u.indexOf("?"));
query = u.substr(u.indexOf("?") + 1);
params= query.split('&');
}else
path = u;
return {
getHost: function(){
var hostexp = /\/\/([\w.-]*)/;
var match = hostexp.exec(path);
if (match != null && match.length > 1)
return match[1];
return "";
},
getPath: function(){
var pathexp = /\/\/[\w.-]*(?:\/([^?]*))/;
var match = pathexp.exec(path);
if (match != null && match.length > 1)
return match[1];
return "";
},
getHash: function(){
return hash;
},
getParams: function(){
return params
},
getQuery: function(){
return query;
},
setHash: function(value){
if(query.length > 0)
query = "?" + query;
if(value.length > 0)
query = query + "#" + value;
return path + query;
},
setParam: function(name, value){
if(!params){
params= new Array();
}
params.push(name + '=' + value);
for (var i = 0; i < params.length; i++) {
if(query.length > 0)
query += "&";
query += params[i];
}
if(query.length > 0)
query = "?" + query;
if(hash.length > 0)
query = query + "#" + hash;
return path + query;
},
getParam: function(name){
if(params){
for (var i = 0; i < params.length; i++) {
var pair = params[i].split('=');
if (decodeURIComponent(pair[0]) == name)
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', name);
},
hasParam: function(name){
if(params){
for (var i = 0; i < params.length; i++) {
var pair = params[i].split('=');
if (decodeURIComponent(pair[0]) == name)
return true;
}
}
console.log('Query variable %s not found', name);
},
removeParam: function(name){
query = "";
if(params){
var newparams = new Array();
for (var i = 0;i < params.length;i++) {
var pair = params[i].split('=');
if (decodeURIComponent(pair[0]) != name)
newparams .push(params[i]);
}
params = newparams;
for (var i = 0; i < params.length; i++) {
if(query.length > 0)
query += "&";
query += params[i];
}
}
if(query.length > 0)
query = "?" + query;
if(hash.length > 0)
query = query + "#" + hash;
return path + query;
},
}
}
document.write("Host: " + URLParser(url).getHost() + '<br>');
document.write("Path: " + URLParser(url).getPath() + '<br>');
document.write("Query: " + URLParser(url).getQuery() + '<br>');
document.write("Hash: " + URLParser(url).getHash() + '<br>');
document.write("Params Array: " + URLParser(url).getParams() + '<br>');
document.write("Param: " + URLParser(url).getParam('myparam1') + '<br>');
document.write("Has Param: " + URLParser(url).hasParam('myparam1') + '<br>');
document.write(url + '<br>');
// Remove the first parameter
url = URLParser(url).removeParam('myparam1');
document.write(url + ' - Remove the first parameter<br>');
// Add a third parameter
url = URLParser(url).setParam('myparam3',3);
document.write(url + ' - Add a third parameter<br>');
// Remove the second parameter
url = URLParser(url).removeParam('myparam2');
document.write(url + ' - Remove the second parameter<br>');
// Add a hash
url = URLParser(url).setHash('newhash');
document.write(url + ' - Set Hash<br>');
// Remove the last parameter
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove the last parameter<br>');
// Remove a parameter that doesn't exist
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove a parameter that doesn\"t exist<br>');
function GetQueryStringParams(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
var tech = GetQueryStringParams('stringtext');
var blog = GetQueryStringParams('stringword');
function loadPageVar (sVar) {
return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
alert(loadPageVar("name"));
var q = {};
location.href.split('?')[1].split('&').forEach(function(i){
q[i.split('=')[0]]=i.split('=')[1];
});
{hello:'world', foo:'bar'}
var getQueryStringData = function(name) {
var result = null;
var regexS = "[\\?&#]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec('?' + window.location.href.split('?')[1]);
if (results != null) {
result = decodeURIComponent(results[1].replace(/\+/g, " "));
}
return result;
};
var url = require('url');
url.parse('http://example.com/?bob=123', true).query;
// returns { "bob": "123" }
const url = new URL('http://example.com/?bob=123');
url.searchParams.get('bob');
var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);
//Iterate the search parameters.
for (let p of searchParams) {
console.log(p);
}
searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.delete("topic");
searchParams.toString(); // "q=URLUtils.searchParams"
var name = Arg.get("name");
var params = Arg.all();
var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {var s = item.split("="), k = s[0], v = s[1] && decodeURIComponent(s[1]); (qd[k] = qd[k] || []).push(v)})
//using ES6 (23 characters cooler)
var qd = {};
if (location.search) location.search.substr(1).split`&`.forEach(item => {let [k,v] = item.split`=`; v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v)})
var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {
var s = item.split("="),
k = s[0],
v = s[1] && decodeURIComponent(s[1]); // null-coalescing / short-circuit
//(k in qd) ? qd[k].push(v) : qd[k] = [v]
(qd[k] = qd[k] || []).push(v) // null-coalescing / short-circuit
})
"?a=1&b=0&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"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
> qd.a[1] // "5"
> qd["a"][1] // "5"
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
"?a=1&b=0&c=3&d&e&a=5"
> queryDict
a: "5"
b: "0"
c: "3"
d: undefined
e: undefined
var qd = {};
location.search.substr(1).split("&").forEach(function(item) {(item.split("=")[0] in qd) ? qd[item.split("=")[0]].push(item.split("=")[1]) : qd[item.split("=")[0]] = [item.split("=")[1]]})
> qd
a: ["1", "5"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined]
var qd = {};
location.search.substr(1).split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v]})
"?a=1&b=0&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"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: ["undefined"] // decodeURIComponent(undefined) returns "undefined" !!!*
e: ["undefined", "http://w3schools.com/my test.asp?name=ståle&car=saab"]
v = v && decodeURIComponent(v);
if (location.search) location.search.substr(1).split("&").forEach(...)
{
"test": "Hello",
"person": {
"0": "neek",
"1": "jeff",
"2": "jim",
"length": 3,
"extra": "john"
},
"test3": "",
"nocache": "1398914891264"
}
getQueryStringKey = function(key) {
return getQueryStringAsObject()[key];
};
getQueryStringAsObject = function() {
var b, cv, e, k, ma, sk, v, r = {},
d = function (v) { return decodeURIComponent(v).replace(/\+/g, " "); }, //# d(ecode) the v(alue)
q = window.location.search.substring(1), //# suggested: q = decodeURIComponent(window.location.search.substring(1)),
s = /([^&;=]+)=?([^&;]*)/g //# original regex that does not allow for ; as a delimiter: /([^&=]+)=?([^&]*)/g
;
//# ma(make array) out of the v(alue)
ma = function(v) {
//# If the passed v(alue) hasn't been setup as an object
if (typeof v != "object") {
//# Grab the cv(current value) then setup the v(alue) as an object
cv = v;
v = {};
v.length = 0;
//# If there was a cv(current value), .push it into the new v(alue)'s array
//# NOTE: This may or may not be 100% logical to do... but it's better than loosing the original value
if (cv) { Array.prototype.push.call(v, cv); }
}
return v;
};
//# While we still have key-value e(ntries) from the q(uerystring) via the s(earch regex)...
while (e = s.exec(q)) { //# while((e = s.exec(q)) !== null) {
//# Collect the open b(racket) location (if any) then set the d(ecoded) v(alue) from the above split key-value e(ntry)
b = e[1].indexOf("[");
v = d(e[2]);
//# As long as this is NOT a hash[]-style key-value e(ntry)
if (b < 0) { //# b == "-1"
//# d(ecode) the simple k(ey)
k = d(e[1]);
//# If the k(ey) already exists
if (r[k]) {
//# ma(make array) out of the k(ey) then .push the v(alue) into the k(ey)'s array in the r(eturn value)
r[k] = ma(r[k]);
Array.prototype.push.call(r[k], v);
}
//# Else this is a new k(ey), so just add the k(ey)/v(alue) into the r(eturn value)
else {
r[k] = v;
}
}
//# Else we've got ourselves a hash[]-style key-value e(ntry)
else {
//# Collect the d(ecoded) k(ey) and the d(ecoded) sk(sub-key) based on the b(racket) locations
k = d(e[1].slice(0, b));
sk = d(e[1].slice(b + 1, e[1].indexOf("]", b)));
//# ma(make array) out of the k(ey)
r[k] = ma(r[k]);
//# If we have a sk(sub-key), plug the v(alue) into it
if (sk) { r[k][sk] = v; }
//# Else .push the v(alue) into the k(ey)'s array
else { Array.prototype.push.call(r[k], v); }
}
}
//# Return the r(eturn value)
return r;
};