js:解析当前页面url的查询参数

假设当前页面的url是

https://www.baidu.com/index.html?query=Tom#app

获取当前URL对象

window.location

打印出的结果

hash: '',
host: 'www.baidu.com',
hostname: 'www.baidu.com',
href: 'https://www.baidu.com/index.html?query=Tom#app',
origin: 'https://www.baidu.com',
pathname: '/index.html',
port: '',
protocol: 'https:',
search: '?query=Tom',
reload()
replace()

创建 URL 对象

var url = new URL("https://www.baidu.com/index.html?query=Tom#app");
console.log(url);
 URL {
  href: 'https://www.baidu.com/index.html?query=Tom#app',
  origin: 'https://www.baidu.com',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'www.baidu.com',
  hostname: 'www.baidu.com',
  port: '',
  pathname: '/index.html',
  search: '?query=Tom',
  searchParams: URLSearchParams { 'query' => 'Tom' },
  hash: '#app' 
}
  
协议 protocol
主机名 hostname
端口 port
主机 host
来源 origin)
文件名 pathname
锚点 hash
查询参数 search

使用 URLSearchParams 解析查询参数

var searchParams = new URLSearchParams("query=Tom");

console.log(searchParams);
// URLSearchParams { 'query' => 'Tom' }

console.log(searchParams.get("query"));
// Tom

使用实例

1、Node端示例

let href = "https://www.baidu.com/index.html?name=Tom";

let url = new URL(href);
let name = url.searchParams.get("name");
console.log(name);
// Tom

2、 浏览器下示例

// https://www.baidu.com/index.html?name=Tom
let url = new URL(window.location.href);
let name = url.searchParams.get("name");
console.log(name);
// Tom

参考
使用JavaScript解析URL的方法示例

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章