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
正则表达式的方式获取在url上参数
function getQueryString(name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
};
return null;
}
unescape函数很好理解,是对URL进行解码。那么为什么参数值是取r[2]呢?这就涉及到JS中match函数的用法了,查了W3school的文档,有这样一句话:如果没有找到任何匹配的文本, match() 将返回 null。否则,它将返回一个数组,其中存放了与它找到的匹配文本有关的信息。该数组的第 0 个元素存放的是匹配文本,而其余的元素存放的是与正则表达式的子表达式匹配的文本。这就很好理解了,我们的match匹配返回的r中第0个元素是匹配的文本,后面的元素是正则子表达式匹配的文本。
调用
假设url='https://www.xxx.com?from=1&ch=1'
我们要获取from的值
var from = getQueryString('from');