BOM – 操作 Query

前言

ASP.NET Core 寫過一篇關於操作 query 的 ASP.NET Core – 操作 Uri 和 Query. 前端偶爾也會需要做出 query.

 

URLSearchParams

之前講 JavaScript – Fetch 就已經有用到 URLSearchParams 了. 但主要是用來生成 query. 這篇 read / write 都講.

Read From URL

const query = new URLSearchParams(location.search);

在前端, search 指的就是 ?Query. 

location.search 返回的是 ?key=value 這樣的 string. 它是還沒有 decode 的哦.

new URLSearchParams 初始化傳入一個 string, 它就會去 parse 它. 這個 string 最好是以 ? 開頭. 或者 search 去掉問號只留下 key=value&key1=value2 這樣.

/path?key=value <-- 這樣就不 ok, 會 parse 失敗哦.

get and getAll

const value =  query.get('key'); // no match return null
const values: string[] = query.getAll('key'); // no match return empty array

getAll 是針對 same key 的情況, 比如 'key=value&key=value2'

獲取到的值都是 decode 好了的.

for of 遍歷

URLSearchParams 是 iterable

for (const [key, value] of query) {
  console.log("key value", [key, value]);
}

如果 same key, 那麼會 loop 2 次.

has, append, delete, toString

const query = new URLSearchParams();
const hasKey = query.has("key");
query.append("key", "= will auto encode"); // auto encode
query.delete("key");
query.append("key", "= will auto encode");
const finalSearch = query.toString(); // not starts with ?
console.log("finalSearch", finalSearch); // key=%3D+will+auto+encode

顧名思義, 留意註釋的部分就可以了

 

 

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