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 hashif (typeof params.nameofparam == 'undefined') {params = jQuery.deparam.fragment(window.location.href);}
if (typeof params.nameofparam != 'undefined') {var paramValue = params.nameofparam.toString();
}};
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"
更新时间:2021年6月-2021年
对于需要所有查询参数的特定情况:
const urlSearchParams = new URLSearchParams(window.location.search);const params = Object.fromEntries(urlSearchParams.entries());
这里发布的一些解决方案效率低下。每次脚本需要访问参数时重复正则表达式搜索是完全没有必要的,一个将参数拆分为关联数组样式对象的函数就足够了。如果你不使用超文本标记语言5 History API,每个页面加载只需要一次。这里的其他建议也无法正确解码URL。
var urlParams;(window.onpopstate = function () {var match,pl = /\+/g, // Regex for replacing addition symbol with a spacesearch = /([^&=]+)=?([^&]*)/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]);})();
A new capability would be to retrieve repeated params as following myparam=1&myparam=2. There is not a specification, however, most of the current approaches follow the generation of an array.
myparam = ["1", "2"]
所以,这是管理它的方法:
let urlParams = {};(window.onpopstate = function () {let match,pl = /\+/g, // Regex for replacing addition symbol with a spacesearch = /([^&=]+)=?([^&]*)/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]);}}})();
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}
(function($) {$.QueryString = (function(paramsArray) {let params = {};
for (let i = 0; i < paramsArray.length; ++i){let param = paramsArray[i].split('=', 2);
if (param.length !== 2)continue;
params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));}
return params;})(window.location.search.substr(1).split('&'))})(jQuery);
用法
//Get a param$.QueryString.param//-or-$.QueryString["param"]//This outputs something like...//"val"
//Get all params as object$.QueryString//This outputs something like...//Object { param: "val", param2: "val" }
//Set a param (only in the $.QueryString object, doesn't affect the browser's querystring)$.QueryString.param = "newvalue"//This doesn't output anything, it just updates the $.QueryString object
//Convert object into string suitable for url a querystring (Requires jQuery)$.param($.QueryString)//This outputs something like...//"param=newvalue¶m2=val"
//Update the url/querystring in the browser's location bar with the $.QueryString objecthistory.replaceState({}, '', "?" + $.param($.QueryString));//-or-history.pushState({}, '', "?" + $.param($.QueryString));
;(function ($) {$.extend({getQueryString: function (name) {function parseParams() {var params = {},e,a = /\+/g, // Regex for replacing addition symbol with a spacer = /([^&=]+)=?([^&]*)/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 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/>");};
function getParameterByName(name) {var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);return match && decodeURIComponent(match[1].replace(/\+/g, ' '));}
if (!window.location.getParameter ) {window.location.getParameter = function(key) {function parseParams() {var params = {},e,a = /\+/g, // Regex for replacing addition symbol with a spacer = /([^&=]+)=?([^&]*)/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];};}
url_args_decode = function (url) {var args_enc, el, i, nameval, ret;ret = {};// use the DOM to parse the URL via an 'a' elementel = document.createElement("a");el.href = url;// strip off initial ? on search and splitargs_enc = el.search.substring(1).split('&');for (i = 0; i < args_enc.length; i++) {// convert + into space, split on =, and then decodeargs_enc[i].replace(/\+/g, ' ');nameval = args_enc[i].split('=', 2);ret[decodeURIComponent(nameval[0])]=decodeURIComponent(nameval[1]);}return ret;};
作为额外的奖励,如果您更改了一些参数,您可以使用第二个函数将参数数组放回URL字符串中:
url_args_replace = function (url, args) {var args_enc, el, name;// use the DOM to parse the URL via an 'a' elementel = document.createElement("a");el.href = url;args_enc = [];// encode args to go into urlfor (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;};
// 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;}
/* 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");
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.
}
var u = new Url; // Current document URL// orvar u = new Url('http://user:pass@example.com:8080/some/path?foo=bar&bar=baz#anchor');
// Looking for query string parametersalert( u.query.bar);alert( u.query.foo);
// Modifying query string parametersu.query.foo = 'bla';u.query.woo = ['hi', 'hey']
alert(u.query.foo);alert(u.query.woo);alert(u);
var querystring = location.search.replace('?', '').split('&');for (var i = 0; i < querystring.length; i++) {var name = querystring[i].split('=')[0];var value = querystring[i].split('=')[1];queryObj[name] = value;}
function getUrlVars() {var vars = {};var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {vars[key] = value;});return vars;}
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)}
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"> qda: ["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"]
function getQueryData(url, paramKey, pairKey, missingValue, decode) {
var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;
if (!url || typeof url !== 'string') {url = location.href; // more robust than location.search, which is flaky}if (!paramKey || typeof paramKey !== 'string') {paramKey = '&';}if (!pairKey || typeof pairKey !== 'string') {pairKey = '=';}// when you do not explicitly tell the API...if (arguments.length < 5) {// it will unescape parameter keys and values by default...decode = true;}
queryStart = url.indexOf('?');if (queryStart >= 0) {// grab everything after the very first ? question mark...query = url.substring(queryStart + 1);} else {// assume the input is already parameter data...query = url;}// remove fragment identifiers...fragStart = query.indexOf('#');if (fragStart >= 0) {// remove everything after the first # hash mark...query = query.substring(0, fragStart);}// make sure at this point we have enough material to do something useful...if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {// we no longer need the whole query, so get the parameters...query = query.split(paramKey);result = {};// loop through the parameters...for (i = 0, len = query.length; i < len; i = i + 1) {pairKeyStart = query[i].indexOf(pairKey);if (pairKeyStart >= 0) {name = query[i].substring(0, pairKeyStart);} else {name = query[i];}// only continue for non-empty names that we have not seen before...if (name && !Object.prototype.hasOwnProperty.call(result, name)) {if (decode) {// unescape characters with special meaning like ? and #name = decodeURIComponent(name);}if (pairKeyStart >= 0) {value = query[i].substring(pairKeyStart + 1);if (value) {if (decode) {value = decodeURIComponent(value);}} else {value = missingValue;}} else {value = missingValue;}result[name] = value;}}return result;}}
function getQueryData(url, paramKey, pairKey, missingValue, decode) {
var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;
if (!url || typeof url !== 'string') {url = location.href; // more robust than location.search, which is flaky}if (!paramKey || typeof paramKey !== 'string') {paramKey = '&';}if (!pairKey || typeof pairKey !== 'string') {pairKey = '=';}// when you do not explicitly tell the API...if (arguments.length < 5) {// it will unescape parameter keys and values by default...decode = true;}
queryStart = url.indexOf('?');if (queryStart >= 0) {// grab everything after the very first ? question mark...query = url.substring(queryStart + 1);} else {// assume the input is already parameter data...query = url;}// remove fragment identifiers...fragStart = query.indexOf('#');if (fragStart >= 0) {// remove everything after the first # hash mark...query = query.substring(0, fragStart);}// make sure at this point we have enough material to do something useful...if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {// we no longer need the whole query, so get the parameters...query = query.split(paramKey);result = {names: [],values: []};// loop through the parameters...for (i = 0, len = query.length; i < len; i = i + 1) {pairKeyStart = query[i].indexOf(pairKey);if (pairKeyStart >= 0) {name = query[i].substring(0, pairKeyStart);} else {name = query[i];}// only continue for non-empty names...if (name) {if (decode) {// unescape characters with special meaning like ? and #name = decodeURIComponent(name);}if (pairKeyStart >= 0) {value = query[i].substring(pairKeyStart + 1);if (value) {if (decode) {value = decodeURIComponent(value);}} else {value = missingValue;}} else {value = missingValue;}result.names.push(name);result.values.push(value);}}return result;}}
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 objectif (typeof v != "object") {//# Grab the cv(current value) then setup the v(alue) as an objectcv = 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 valueif (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 existsif (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) locationsk = 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 itif (sk) { r[k][sk] = v; }//# Else .push the v(alue) into the k(ey)'s arrayelse { Array.prototype.push.call(r[k], v); }}}
//# Return the r(eturn value)return r;};