- 网址的拆分及获取
<script>
function queryURLParams(url){
let askIndex=url.indexOf('?'),
polIndex=url.lastIndexOf('#'),
askText='',
polText='';
//#号不存在
polIndex===-1?polIndex=url.length:null;
polText=url.substring(polIndex+1);
if(askIndex>-1){
askText=url.substring(askIndex+1,polIndex);
}
let obj={};
polText.length>0?obj['HASH']=polText:null;
if(askText){
askText.split('&').forEach(item=>{
let arr=item.split('='),
key=arr[0],
value=arr[1];
obj[key]=value;
});
}
return obj;
}
let result=queryURLParams('http://www.baidu.com/?lx=1&name=JS&from=baidu#video');
console.log(result);
</script>
- 创建A标签的形式
<script>
function queryURLParams(url){
//1.创建A标签来获取问号参数和哈希值
let link=document.createElement('a');
link.href=url;
let askText=link.search.substr(1),
polText=link.hash.substr(1);
let obj={};
//2.向对象中进行存储
polText?obj['HASH']=polText:null;
if(askText){
let arr=askText.split(/(?:&|=)/g);
for(let i=0;i<arr.length;i+=2){
obj[arr[i]]=arr[i+1]; //属性名和属性值
}
}
return obj;
}
let result=queryURLParams('http://www.baidu.com/?lx=1&name=JS&from=baidu#video');
console.log(result);
</script>
效果图:
- 正则
<script>
(proto=>{
function queryURLParams(){
let obj={};
this.replace(/([^?=&#]+)=([^?=&#]+)/g,(_,key,value)=>obj[key]=value);
this.replace(/#([^?&=#]+)/g,(_,hash)=>obj['HASH']=hash);
return obj;
}
proto.queryURLParams=queryURLParams;
})(String.prototype);
console.log('http://www.baidu.com/?lx=1&name=JS&from=baidu#video'.queryURLParams());
</script>
效果图如下: