美文网首页前端交流圈
js获取url中指定参数的值(兼容hash)

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

作者: lulu_c | 来源:发表于2020-01-02 14:45 被阅读0次

什么是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;
}

相关文章

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

    什么是window.location? 示例:*URL:https://www.baidu.com/?name=2...

  • JavaScript 获取url,html文件名,参数值

    1、获取url: 2、获取url中的文件名: 3、获取url中的指定参数的值:jquery从html路径中获取参数...

  • 在路由中截取网址参数

    1.vuejs取得URL中参数的值 2. js获取URL中的参数 js获取URL中的一些参数的意思location...

  • 获取指定url参数

    获取指定url参数 获取指定url的指定参数 浏览器类型

  • js日常方法总结

    封装函数 f,使 f 的 this 指向指定的对象 获取 url 中的参数 指定参数名称,返回该参数的值 或者 空...

  • 获取url中的参数

    获取 url 中的参数 指定参数名称,返回该参数的值 或者 空字符串 不指定参数名称,返回全部的参数对象 或者 {...

  • js操作浏览器Url

    1.获取url中的参数 2.在指定url栏附加参数或替换参数值 3.删除Url中的指定参数

  • 练习1--解析URL参数

    题目描述获取 url 中的参数 指定参数名称,返回该参数的值 或者 空字符串 不指定参数名称,返回全部的参数对象 ...

  • url模块

    url模块 url.hash 获取及设置URL的分段(hash)部分。 包含在赋给hash属性的值中的无效URL字...

  • 牛客网前端大挑战题解

    一、获取 url 中的参数1. 指定参数名称,返回该参数的值 或者 空字符串2. 不指定参数名称,返回全部的参数对...

网友评论

    本文标题:js获取url中指定参数的值(兼容hash)

    本文链接:https://www.haomeiwen.com/subject/yrjioctx.html