【Js】获取地址栏参数(超简单)

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

属性描述
hash设置或返回从井号 (#) 开始的 URL(锚)。
host设置或返回主机名和当前 URL 的端口号。
hostname设置或返回当前 URL 的主机名。
href设置或返回完整的 URL。
pathname设置或返回当前 URL 的路径部分。
port设置或返回当前 URL 的端口号。
protocol设置或返回当前 URL 的协议。
search设置或返回从问号 (?) 开始的 URL(查询部分)。

2、为什么 window.location.search 为空?

答:注意search和hash的区别,
如果URL中“?”之前有一个“#”比如:“http://localhost:63342/index.html#/version?type=35&id=5”,
那么使用window.location.search得到的就是空(“”)。
因为“?type=35&id=5”是属于“#/version?type=35&id=5”这个串字符的,
也就是说查询字符串search只能在取到“?”后面和“#”之前这个区间的内容,如果“#”之前没有“?”,search取值为空。

3、采用正则表达式获取地址栏参数:

function getUrlSearch(name) {
  // 未传参,返回空
  if (!name) return null;
  // 查询参数:先通过search取值,如果取不到就通过hash来取
  var after = window.location.search;
  after = after.substr(1) || window.location.hash.split('?')[1];
  // 地址栏URL没有查询参数,返回空
  if (!after) return null;
  // 如果查询参数中没有"name",返回空
  if (after.indexOf(name) === -1) return null;

  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
  // 当地址栏参数存在中文时,需要解码,不然会乱码
  var r = decodeURI(after).match(reg);
  // 如果url中"name"没有值,返回空
  if (!r) return null;

  return r[2];
}

// 调用方法
getUrlSearch("参数名");

// 举例1:若地址栏URL为:abc.html?id=123&name=池子&url=http://www.baidu.com
console.log('地址栏参数id',getUrlSearch("id"));
console.log('地址栏参数name',getUrlSearch("name"));
console.log('地址栏参数url',getUrlSearch("ursl"));
// 123
// 池子(不解码此处是乱码)
// null


// 举例2:若地址栏URL为:abc.html
console.log('地址栏参数id',getUrlSearch("id"));
// null

 

  • 9
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

smart_dream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值