new URLSearchParams() 获取地址栏的参数 通过键的方式拿到值

通常通过window.location 获取页面的 URL 地址。
首先简单说明一下 window.location

window.location

比如URL:http://b.a.com:88/index.php?name=kang&when=2011#first

在这里插入图片描述
window.locationdocument.location 互相等价的,可以交换使用。

search:"?name=kang&how=" 第一个"?"之后

hash:"#when=2011#first" 第一个"#"之后的内容

疑问:
为什么有时候 window.location.search 为空?
注意上面的 searchhash 的区别,如果URL中 ? 之前有一个 # 比如:“http://localhost:8081/#/ApplyForm?companyId=32&storeId=3129”,那么使用window.location.search得到的就是空(‘’)。因为“companyId=32&storeId=3129”串字符是属于“#/ApplyForm?companyId=32&storeId=3129”这个串字符的,也就是说查询字符串search只能在取到 ? 后面和 # 之前的内容,如果“#”之前没有“?”search取值为空。

正题:new URLSearchParams()

1、可通过 location.searchlocaton.hash 处理URL来获取到参数组成的字符串。
2、然后通过 new URLSearchParams() 方法处理字符串得到。
3、通过 get("id") 方法可得到对应参数

let urlSearch = '?companyId=32&storeId=3129' // 经过处理过的 url 参数字符串
let objParams = new URLSearchParams(urlSearch)
let companyId = objParams.get('companyId ') // 32
let storeId = objParams.get('storeId') // 3129

获取参数的方法还可通过 Object.fromeEntries() 来获取参数对象

Object.fromEntries(new URLSearchParams(objParams) // {companyId: 32, storeId: 3129}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值