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的方法示例

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