functionqueryURLParams(url){// 创建a标签(A元素)来获取问号参数和哈希值let link = document.createElement('a');
link.href = url;// 面向对象let askText = link.search.substr(1),// 拿到的是‘?xxxx’
wellText = link.hash.substr(1),//拿到的是‘#xxxx’
obj ={};// 向对象中进行存储
wellText ? obj['HASH']= wellText :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;}
Solution 3(正则)
测试用例
// case 1: ? #let result =queryURLParams('https://sports.qq.com/kbsweb/game.htm?lx=1&name=ty#55055776');
console.log(result);// case 2: #let result2 =queryURLParams('https://sports.qq.com/kbsweb/game.htm#55055777');
console.log(result2);// case 3: ?let result3 =queryURLParams('https://sports.qq.com/kbsweb/game.htm?lx=1&name=ty');
console.log(result3);