前端交流圈

js获取url中指定参数的值(兼容hash)

2020-01-02  本文已影响0人  lulu_c

什么是window.location?

示例:
*URL:https://www.baidu.com/?name=21002492_21_hao_pg

属性 含义
protocol: 协议 "https:"
hostname: 服务器的名字 "www.baidu.com"
port: 端口 ""
pathname: URL中主机名后的部分 "/"
search: "?"后的部分,又称为查询字符串 "?tn=21002492_21_hao_pg"
hash: 返回"#"之后的内容 ""
host: 等于hostname + port "www.baidu.com"
href: 当前页面的完整URL "https://www.baidu.com/?name=21002492_21_hao_pg"

window.location和document.location互相等价的,可以交换使用

location的8个属性都是可读写的,但是只有href与hash的写才有意义。例如改变location.href会重新定位到一个URL,而修改location.hash会跳到当前页面中的anchor(<a id="name">或者<div id="id">等)名字的标记(如果有),而且页面不会被重新加载

注意
URL:https://www.baidu.com/?name=21002492_21_hao_pg#test?test1=1

search:"?name=21002492_21_hao_pg" 第一个"?"之后

hash:"#test?test1=1" 第一个"#"之后的内容

为什么 window.location.search 为空?

注意上面的search和hash的区别,如果URL中“?”之前有一个“#”比如:“https://www.baidu.com/#/test?name=21002492_21_hao_pg”那么使用window.location.search得到的就是空(“”)。因为“?name=21002492_21_hao_pg”串字符是属于“#/test?name=21002492_21_hao_pg”这个串字符的,也就是说查询字符串search只能在取到“?”后面和“#”之前的内容,如果“#”之前没有“?”search取值为空。

怎么获取url的?后面的参数

现在前端会使用大量的框架来搭建前端页面应用,比如vue,当开启hash模式的时候,在实例外部方法无法使用this.$route时,老方法window.location.search也获取不到,这时需要使用window.location.hash来获取参数

兼容hash模式与非hash模式的方法:

getQueryString = (name, search) => {
  search = search ||  window.location.search.substr(1) || window.location.hash.split("?")[1];
  let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
  let r = search.match(reg);
  if (r != null) return  unescape(r[2]); return null;
}
上一篇下一篇

猜你喜欢

热点阅读