1、获取地址栏url参数方法
function getQueryString(field) { let searchStr = window.location.search if (!field || !searchStr) return null let reg = new RegExp('(^|&)' + field + '=([^&]*)(&|$)') let res = searchStr.substring(1).match(reg) return res !== null ? decodeURIComponent(res[2]) : null }
栗子:https://jiangdesheng.com/aa/bc?token=123456&pid=85
使用getQueryString("token")就能得到123456
2、解析url参数为Object
/** * 解析url参数 * @example ?id=12345&a=b * @return Object {id:12345,a:b} */ function urlParse(url) { let obj = {} let reg = /[?&][^?&]+=[^?&]+/g let arr = url.match(reg) if (arr) { arr.forEach((item) => { let tempArr = item.substring(1).split('=') let key = decodeURIComponent(tempArr[0]) let val = decodeURIComponent(tempArr.splice(1).join('=')) obj[key] = val }) } return obj }
有朋自远方来...评论一下呗O(∩_∩)O