js 截取url中的参数

getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if(r != null) {
        return unescape(r[2]);
    }
    return null;
}

正常的页面可以调用这个方法,window.location.search获取到当前页面从问号 (?) 开始的 URL(查询部分)

随后配合正则就可以筛选出想要的参数,比如链接:https://i.cnblogs.com/EditPosts.aspx?hello=123

这么使用:  getQueryString(‘hello’)

就可以直接获取到  “123”

--------------------------------------------------------------

这个方法在vue单页面中是不可用的,比如vue的hash模式,链接是含有#号且在?号之前的

比如: http://192.168.1.181:8080/#/bookDetail?antBook=3

如果这时候调用方法:this.getQueryString(‘antBook’),是会返回null的,主要原因是该死的#号,他会让window.location.search直接失效,阻碍我们导致

根本拿不到我们想要的antBook的值

这个时候也很简单,我们只要相对的改改代码,让从问号 (?) 开始变为从#号开始的 URL(锚)

也就是将(window.location.search)更改为(window.location.hash

这样在vue单页面中,就可以顺利取到参数值了

猜你喜欢

转载自www.cnblogs.com/DangerousBaymax/p/9265129.html
今日推荐