js 获取url及参数

Location 对象是 Window 对象的一个部分,可通过 window.location 属性来访问。

参数含义
hash设置或返回从井号 (#) 开始的 URL(锚)。
host设置或返回主机名和当前 URL 的端口号。
hostname设置或返回当前 URL 的主机名。
href设置或返回完整的 URL。
pathname设置或返回当前 URL 的路径部分。
port设置或返回当前 URL 的端口号。
protocol设置或返回当前 URL 的协议。
search设置或返回从问号 (?) 开始的 URL(查询部分)。
一 . 如何获取#号后的字符串
  1. window.location.search:获取当前URL的'?'号开始的字符串

  2. window.location.hash:获取当前URL的'#'后面的字符串

二 .js代码
//1.获取链接后的参数(不带#号)
getQueryString(name) {
   let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}
复制代码
//2.获取链接后的参数(带#号)
getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    if(window.location.hash.indexOf("?") < 0){
    return null;
    }
    let r = window.location.hash.split("?")[1].match(reg); &emsp;&emsp;
    if (r != null) return decodeURIComponent(r[2]); 
&emsp;&emsp;return null; 
}
复制代码
//3.使用
console.log('name is ',getQueryString('name'));
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值