是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
我宁愿使用split()而不是Regex执行此操作:
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;
}
其他回答
Node.js的源代码中有一个健壮的实现https://github.com/joyent/node/blob/master/lib/querystring.js
TJ的qs也执行嵌套参数解析https://github.com/visionmedia/node-querystring
我需要查询字符串中的一个对象,我讨厌很多代码。它可能不是世界上最健壮的,但它只是几行代码。
var q = {};
location.href.split('?')[1].split('&').forEach(function(i){
q[i.split('=')[0]]=i.split('=')[1];
});
像这样的URL.htm?hello=world&foo=bar将创建:
{hello:'world', foo:'bar'}
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;
};
查看此帖子或使用此:
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
var urlParams = {};
(function ()
{
var match,
pl= /\+/g, // Regular expression 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))
urlParams[decode(match[1])] = decode(match[2]);
})();
if (urlParams["q1"] === 1)
{
return 1;
}
});
</script>
我在这里做了一个小的URL库来满足我的需求:https://github.com/Mikhus/jsurl
这是一种在JavaScript中操纵URL的更常见的方法。同时,它非常轻量级(缩小和gzip<1KB),并且具有非常简单和干净的API。而且它不需要任何其他库来工作。
关于最初的问题,很简单:
var u = new Url; // Current document URL
// or
var u = new Url('http://user:pass@example.com: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);