开发中少不了的Fun -- 获取地址栏URL参数

时间:2023-03-08 17:59:09
开发中少不了的Fun -- 获取地址栏URL参数
假设这是一个url地址 http://localhost:8080/a/b/c?a=1&b=2#abc,里面包含的部分:

        protocol: 'http:',  // 协议
host: 'localhost:8080', // 主机
port: '8080', // 端口
hostname: 'localhost', // 主机名称
hash: '#abc',
search: '?a=1&b=2',
query: 'a=1&b=2',
pathname: '/a/b/c',
path: '/a/b/c?a=1&b=2',
href: 'http://localhost:8080/a/b/c?a=1&b=2#abc' // 超链接 decodeURIComponent() 对编码后的 URI 进行解码,
encodeURIComponent() 函数可把字符串作为 URI 组件进行编码,
encodeURI()不会对本身属于URI的特殊字符进行编码,例如冒号、正斜杠、问号和井字号;而encodeURIComponent()则会对它发现的任何非标准字符进行编码, location 对象包含有关当前 URL 的信息,
location 对象是 Window 对象的一个部分,可通过 window.location 属性来访问,

将地址栏url的query解析成对象

        function urlSlice(url){
if(url.indexOf('?') == -1){
return false;
}
var arr = decodeURIComponent(url).split("?");
arr = arr[1].split("&");
var len = arr.length, obj={};
for(var i = 0;i < len;i++){
var a = arr[i].split("=");
obj[a[0]] = a[1];
}
return obj;
}
var objUrl = urlSlice(location.href);
console.log(objUrl);
GetQueryString: function (name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
},

清楚跳转链接历史记录

fnUrlReplace(href) {
if (href && /^#|javasc/.test(href) === false) {
if (history.replaceState) {
history.replaceState(null, document.title, href.split('#')[0] + '#');
location.replace('');
} else {
location.replace(href);
}
}
}