Skip to content
On this page

location

js
location.protocol // https:
location.host // www.google.com
location.origin // https://www.google.com
location.search // ?q=hello
location.hash // [[router-hash]]
location.pathname // /search

解析或封装 URL 查询参数:

js
let query = `q=测试&order=asc&list=["ES", "US"]`
const params = new URLSearchParams(query)
console.log(params)
for(let p of params){
	console.log(p) // ['q', '测试'].....
}
console.log(params.get("q")) // 测试
console.log(params.get("list")) // ["ES", "US"],这是字符串
console.log(JSON.parse(params.get("list")))// ["ES", "US"],数组
console.log(params.has("order")) // true
console.log(params.toString()) // q=%E6%B5%8B%E8%AF%95&order=asc&list=%5B%22ES%22%2C+%22US%22%5D
params.set("order", "desc") // 修改
params.append("pageSize", "10") // 追加
params.delete("pageSize") // 删除

解析 URL 参数

2022年了!你有几种获取URL参数的方法? - 知乎 (zhihu.com)

Released under the MIT License.