F12在console选项卡里面输入下面的两行代码:
const getUrlParam = a => (a = location.search.substr(1).match(new RegExp(`(^|&)${a}=([^&]*)(&|$)`)),a?a[2]:null);
const getUrlParams = url => {let reg = /([^=&\s]+)[=\s]*([^&\s]*)/g, ls = url || location.search.substr(1), obj = {};while (reg.exec(ls)) obj[RegExp.$1] = decodeURIComponent(RegExp.$2);return obj;};
回车后运行
getUrlParam('wd')
decodeURIComponent(getUrlParam('wd'))
getUrlParams()
显示如下内容
有一种情况如果是使用了vue或者Angular框架的hash模式路由
直接用上面的getUrlParam和getUrlParams方法不能获取url?后面的queryparams参数内容
需要对getUrlParam和getUrlParams两个方法简单重构,代码修改如下,就可以适配vue或Angular框架了
const getUrlParam = a => (a = (location.search?location.search.substr(1):(location.hash.split('?')[1]||'')).match(new RegExp(`(^|&)${a}=([^&]*)(&|$)`)),a?a[2]:null);//兼容vue和Angular的hash模式url参数格式
const getUrlParams = url => {let reg = /([^=&\s]+)[=\s]*([^&\s]*)/g, ls = url || (location.search?location.search.substr(1):(location.hash.split('?')[1]||'')), obj = {};while (reg.exec(ls)) obj[RegExp.$1] = decodeURIComponent(RegExp.$2);return obj;};//兼容vue和Angular的hash模式url参数格式
核心调整代码为 (location.search?location.search.substr(1):(location.hash.split('?')[1]||''))
这样在vue或Angular框架体系下就兼容获取浏览器地址的参数了。
当然,如果你想用vue和Angular框架自带的对象来获取网页浏览器地址url后面的参数,您还可以通过下面的链接了解更多
API 参考 | Vue RouterVue.js 的官方路由