js获取url地址中的每一个参数,方便操作url的hash
值得收藏
<html>
<body>
<script>
//location.search; //可获取浏览器当前访问的url中"?"符后的字串
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'), //将该字符串首位的?替换成空然后根据&来分隔返回一个数组
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) {
continue;
}
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^\/])/,'/$1'),//将该字符串首位不是/的用这个组([^\/])替换,$1代表出现在正则表达式中的第一个()、$2代表出现在正则表达式中的第二个()...
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^\//,'').split('/') };
}
var URL = parseURL('http://abc.com:8080/dir/index.html?pid=255&m=hello#top&ab=1');
// var URL = parseURL('http://localhost:8080/test/mytest/toLogina.ction?m=123&pid=abc');
console.log('URL.query', URL.query)
console.log('URL.path', URL.path);
console.log('URL.hash', URL.hash);
console.log('URL.params.pid', URL.params.pid);
</script>
</body>
</html>
参考:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace