假设有如下地址:http://127.0.0.1:8080/index.html?id=14&id2=20/#/desktop/agents-task-xd?userId=aaa&userId2=bbb
需要获取id、id2、userId、userId2的数据:
console.log('getQueryString', getQueryString('id')) // 14 console.log('getQueryString', getQueryString('id2')) // 20 console.log('getHashString', getHashString('userId')) // aaa console.log('getHashString', getHashString('userId2')) // bbb // 获取URL中的query传参: function getQueryString(name){ var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); var r = window.location.search.substr(1).match(reg); if (r != null) { let str = unescape(r[2]); if(str.indexOf('/') > -1) { str = str.substr(0, str.length-1) } return str } return null; } // 获取URL中hash后面的传参: function getHashString(name){ var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); let hash = window.location.hash.split('?')[1] if(!hash) return null hash = '?'+hash var r = hash.substr(1).match(reg); if (r != null) { let str = unescape(r[2]); if(str.indexOf('/') > -1) { str = str.substr(0, str.length-1) } return str } return null; }