URLSearchParams

Baseline 廣泛可用 *

此功能已成熟,可跨多種裝置和瀏覽器版本工作。它自 ⁨2018 年 4 月⁩ 起已在所有瀏覽器中可用。

* 此特性的某些部分可能存在不同級別的支援。

注意:此功能在 Web Workers 中可用。

URLSearchParams 介面定義了用於處理 URL 查詢字串的實用方法。

URLSearchParams 物件是 可迭代的,因此它們可以直接用於 for...of 結構中,以與查詢字串中出現的順序相同的順序遍歷鍵/值對,例如,以下兩行是等效的:

js
for (const [key, value] of mySearchParams) {
}
for (const [key, value] of mySearchParams.entries()) {
}

儘管 URLSearchParams 在功能上與 Map 類似,但在迭代時,由於其實現方式,它可能會遇到一些 Map 不會遇到的 陷阱

建構函式

URLSearchParams()

返回一個 URLSearchParams 物件例項。

例項屬性

size 只讀

指示搜尋引數條目的總數。

例項方法

URLSearchParams[Symbol.iterator]()

返回一個 iterator,允許按查詢字串中出現的順序遍歷此物件中包含的所有鍵/值對。

URLSearchParams.append()

將指定的鍵/值對作為新的搜尋引數附加。

URLSearchParams.delete()

從所有搜尋引數列表中刪除名稱和可選值匹配的搜尋引數。

URLSearchParams.entries()

返回一個 iterator,允許按查詢字串中出現的順序遍歷此物件中包含的所有鍵/值對。

URLSearchParams.forEach()

允許透過回撥函式遍歷此物件中包含的所有值。

URLSearchParams.get()

返回與給定搜尋引數關聯的第一個值。

URLSearchParams.getAll()

返回與給定搜尋引數關聯的所有值。

URLSearchParams.has()

返回一個布林值,指示給定的引數或引數和值對是否存在。

URLSearchParams.keys()

返回一個 iterator,允許遍歷此物件中包含的鍵/值對的所有鍵。

URLSearchParams.set()

將與給定搜尋引數關聯的值設定為給定的值。如果存在多個值,則刪除其他值。

URLSearchParams.sort()

按鍵對所有鍵/值對(如果有)進行排序。

URLSearchParams.toString()

返回一個包含適合在 URL 中使用的查詢字串的字串。

URLSearchParams.values()

返回一個 iterator,允許遍歷此物件中包含的鍵/值對的所有值。

示例

使用 URLSearchParams

js
const paramsString = "q=URLUtils.searchParams&topic=api";
const searchParams = new URLSearchParams(paramsString);

// Iterating the search parameters
for (const p of searchParams) {
  console.log(p);
}

console.log(searchParams.has("topic")); // true
console.log(searchParams.has("topic", "fish")); // false
console.log(searchParams.get("topic") === "api"); // true
console.log(searchParams.getAll("topic")); // ["api"]
console.log(searchParams.get("foo") === null); // true
console.log(searchParams.append("topic", "webdev"));
console.log(searchParams.toString()); // "q=URLUtils.searchParams&topic=api&topic=webdev"
console.log(searchParams.set("topic", "More webdev"));
console.log(searchParams.toString()); // "q=URLUtils.searchParams&topic=More+webdev"
console.log(searchParams.delete("topic"));
console.log(searchParams.toString()); // "q=URLUtils.searchParams"

搜尋引數也可以是一個物件。

js
const paramsObj = { foo: "bar", baz: "bar" };
const searchParams = new URLSearchParams(paramsObj);

console.log(searchParams.toString()); // "foo=bar&baz=bar"
console.log(searchParams.has("foo")); // true
console.log(searchParams.get("foo")); // "bar"

解析 window.location

URL 不同,Location 介面不提供現成的 searchParams 屬性。我們可以使用 URLSearchParams 解析 location.search

js
// Assume page has location:
// https://mdn.club.tw/en-US/docs/Web/API/URLSearchParams?foo=a
const paramsString = window.location.search;
const searchParams = new URLSearchParams(paramsString);
console.log(searchParams.get("foo")); // a

重複的搜尋引數

js
const paramStr = "foo=bar&foo=baz";
const searchParams = new URLSearchParams(paramStr);

console.log(searchParams.toString()); // "foo=bar&foo=baz"
console.log(searchParams.has("foo")); // true
console.log(searchParams.get("foo")); // bar, only returns the first value
console.log(searchParams.getAll("foo")); // ["bar", "baz"]

無 URL 解析

URLSearchParams 建構函式解析完整的 URL。但是,如果存在,它會剝離字串開頭的 ?

js
const paramsString1 = "http://example.com/search?query=%40";
const searchParams1 = new URLSearchParams(paramsString1);

console.log(searchParams1.has("query")); // false
console.log(searchParams1.has("http://example.com/search?query")); // true

console.log(searchParams1.get("query")); // null
console.log(searchParams1.get("http://example.com/search?query")); // "@" (equivalent to decodeURIComponent('%40'))

const paramsString2 = "?query=value";
const searchParams2 = new URLSearchParams(paramsString2);
console.log(searchParams2.has("query")); // true

const url = new URL("http://example.com/search?query=%40");
const searchParams3 = new URLSearchParams(url.search);
console.log(searchParams3.has("query")); // true

百分比編碼

URLSearchParams 物件會 application/x-www-form-urlencoded 的百分比編碼集(包含除 ASCII 字母數字、*-._ 之外的所有碼點)中的任何內容進行百分比編碼,並將 U+0020 空格編碼為 +。但是,它僅在序列化和反序列化完整的 URL 搜尋引數語法時處理百分比編碼。在與單個鍵和值互動時,您始終使用未編碼的版本。

js
// Creation from parsing a string: percent-encoding is decoded
const params = new URLSearchParams("%24%25%26=%28%29%2B");
// Retrieving all keys/values: only decoded values are returned
console.log([...params]); // [["$%&", "()+"]]
// Getting an individual value: use the decoded key and get the decoded value
console.log(params.get("$%&")); // "()+"
console.log(params.get("%24%25%26")); // null
// Setting an individual value: use the unencoded key and value
params.append("$%&$#@+", "$#&*@#()+");
// Serializing: percent-encoding is applied
console.log(params.toString());
// "%24%25%26=%28%29%2B&%24%25%26%24%23%40%2B=%24%23%26*%40%23%28%29%2B"

如果附加一個帶有百分比編碼鍵的鍵/值對,該鍵將被視為未編碼並再次進行編碼。

js
const params = new URLSearchParams();

params.append("%24%26", "value");
params.toString(); // "%2524%2526=value"

保留加號

URLSearchParams 建構函式將加號 (+) 解釋為空格,這可能會導致問題。在下面的示例中,我們使用 十六進位制轉義序列 來模擬包含二進位制資料(其中每個位元組都包含資訊)的字串,該字串需要儲存在 URL 搜尋引數中。請注意 btoa() 生成的編碼字串包含 +,但 URLSearchParams 未保留它。

js
const rawData = "\x13à\x17@\x1F\x80";
const base64Data = btoa(rawData); // 'E+AXQB+A'

const searchParams = new URLSearchParams(`bin=${base64Data}`); // 'bin=E+AXQB+A'
const binQuery = searchParams.get("bin"); // 'E AXQB A', '+' is replaced by spaces

console.log(atob(binQuery) === rawData); // false

切勿使用動態插值字串構建 URLSearchParams 物件。而是使用 append() 方法,如上所述,該方法將所有字元按原樣解釋。

js
const rawData = "\x13à\x17@\x1F\x80";
const base64Data = btoa(rawData); // 'E+AXQB+A'

const searchParams = new URLSearchParams();
searchParams.append("bin", base64Data); // 'bin=E%2BAXQB%2BA'
const binQuery = searchParams.get("bin"); // 'E+AXQB+A'

console.log(atob(binQuery) === rawData); // true

與 URL.searchParams 的互動

URL.searchParams 屬性將 URL 的 search 字串公開為 URLSearchParams 物件。更新此 URLSearchParams 時,URL 的 search 會隨其序列化而更新。但是,URL.search 編碼的字元子集與 URLSearchParams 不同,並且將空格編碼為 %20 而不是 +。這可能會導致一些意外的互動——如果您更新 searchParams,即使值相同,URL 的序列化方式也可能不同。

js
const url = new URL("https://example.com/?a=b ~");
console.log(url.href); // "https://example.com/?a=b%20~"
console.log(url.searchParams.toString()); // "a=b+%7E"
// This should be a no-op, but it changes the URL's query to the
// serialization of its searchParams
url.searchParams.sort();
console.log(url.href); // "https://example.com/?a=b+%7E"

const url2 = new URL("https://example.com?search=1234&param=my%20param");
console.log(url2.search); // "?search=1234&param=my%20param"
url2.searchParams.delete("search");
console.log(url2.search); // "?param=my+param"

空值與無值

URLSearchParams 不區分沒有 = 之後內容的引數與根本沒有 = 的引數。

js
const emptyVal = new URLSearchParams("foo=&bar=baz");
console.log(emptyVal.get("foo")); // returns ''
const noEquals = new URLSearchParams("foo&bar=baz");
console.log(noEquals.get("foo")); // also returns ''
console.log(noEquals.toString()); // 'foo=&bar=baz'

規範

規範
URL
# urlsearchparams

瀏覽器相容性

另見