动态

详情 返回 返回

如何方便的從 URL 中,獲取指定的參數? - 动态 详情

ES6 提供了一個 URLSearchParams">URLSearchParams 對象,接收一個 URL 的查詢字符串。

如果將 window.location.search 傳入後,再通過實體的 get() 方法。

即可方便的獲取當前頁面路徑中對應參數的值。

// 假設當前頁面鏈接為: 
// https://fehub.com/?name=lmx&age=18&book=santi&book=mingchaonaxieshier
const searchParams = new URLSearchParams(window.location.search);

console.log(searchParams.get("name"));
// lmx

console.log(searchParams.get("age"));
// 18

console.log(searchParams.getAll('book'));
// ['santi', 'mingchaonaxieshier']

URLSearchParams

細心的小夥伴可能知道:window.location.search 獲取到的值是從 ? 開始的字符串。

但是不用擔心,URLSearchParams 會自動移除字符串起始位置的 ?

當然,URLSearchParams 除了可以方便的獲取 URL 參數外,也能方便的修改參數。

// 假設當前頁面鏈接為: 
// https://fehub.com/?name=lmx&age=18&book=santi&book=mingchaonaxieshier&lang=zh_CN
const searchParams = new URLSearchParams(window.location.search);

// 添加參數
searchParams.append("foo", "bar");

// 刪除參數
searchParams.delete("lang");

// 輸出
searchParams.toString(); 
// "name=lmx&age=18&book=santi&book=mingchaonaxieshier&foo=bar"

URLSearchParams Instance methods

是的,聰明的你肯定發現了,toString() 輸出的內容也不會包含 ?


好了,這就是今天分享的全部內容啦 ~

關注我,每天學一個有趣的小知識 😉

微信掃一掃,關注「FEHub」

Add a new 评论

Some HTML is okay.