Js获取Url地址参数的几种方法

方法一 URLSearchParams()函数

geturlparam(){
        let that=this
        // window.location.href 获取地址
        let url = 'https://xxxx.com/xxx/demo?type=1&id=2'
        let p=url.split('?')[1]
        let params=new URLSearchParams(p)
        console.log(params.get('type')) //1
        console.log(params.get('id'))   //2
      }

方法二 split()截取

 geturlparam() {
        let that = this
        // window.location.href 获取地址
        let url = 'https://xxxx.com/xxx/demo?type=1&id=2'
        let p = url.split('?')[1]
        let keyValue = p.split('&');
        let obj = {};
        for (let i = 0; i < keyValue.length; i++) {
          let item = keyValue[i].split('=');
          let key = item[0];
          let value = item[1];
          obj[key] = value;
        }
        console.log(keyValue); //  ['type=1','id=2']
        console.log(obj);      //  {type:'1',id:'2'}
      },

上述两种方法的地址是比较规范的,像只以 / 连接的地址我一般是这种方法,也是split截取

geturlparam() {
        let that = this
        // window.location.href 获取地址
        let url = 'https://xxxx.com/xxx/demo/type/1/id/2'
        if (url.indexOf('/type/') != -1) {
          that.type = url.split("/type/")[1].split("/")[0]; //1
          that.id = url.split("/id/")[1].split("/")[0]; //2
        }
      },

split比较随心所欲,看自己业务需求,想怎么截就怎么截

  • 3
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值