encodeURIComponent()
encodeURIComponent() 函式透過將某些字元的每個例項替換為一個、兩個、三個或四個表示該字元 UTF-8 編碼的轉義序列來編碼 URI(對於由兩個代理字元組成的字元,只會是四個轉義序列)。與 encodeURI() 相比,此函式編碼的字元更多,包括那些作為 URI 語法一部分的字元。
試一試
// Encodes characters such as ?,=,/,&,:
console.log(`?x=${encodeURIComponent("test?")}`);
// Expected output: "?x=test%3F"
console.log(`?x=${encodeURIComponent("шеллы")}`);
// Expected output: "?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"
語法
encodeURIComponent(uriComponent)
引數
uriComponent-
一個字串,要編碼為 URI 元件(路徑、查詢字串、片段等)。其他值會轉換為字串。
返回值
一個新字串,表示提供的 uriComponent 編碼為 URI 元件。
異常
描述
encodeURIComponent() 是全域性物件的函式屬性。
encodeURIComponent() 使用與 encodeURI() 中描述的相同的編碼演算法。它會轉義除以下字元之外的所有字元
A–Z a–z 0–9 - _ . ! ~ * ' ( )
與 encodeURI() 相比,encodeURIComponent() 轉義的字元集更大。將 encodeURIComponent() 用於傳送到伺服器的表單中的使用者輸入欄位——這將編碼在資料輸入過程中可能無意生成的 & 符號,用於字元引用或其他需要編碼/解碼的字元。例如,如果使用者輸入 Jack & Jill,沒有 encodeURIComponent(),伺服器可能會將 & 解釋為新欄位的開始,從而危及資料完整性。
對於 application/x-www-form-urlencoded,空格應替換為 +,因此可能需要在 encodeURIComponent() 替換後,再將 %20 替換為 +。
示例
Content-Disposition 和 Link 頭的編碼
以下示例提供了 UTF-8 Content-Disposition 和 Link 伺服器響應頭引數(例如 UTF-8 檔名)所需的特殊編碼
const fileName = "my file(2).txt";
const header = `Content-Disposition: attachment; filename*=UTF-8''${encodeRFC5987ValueChars(
fileName,
)}`;
console.log(header);
// "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
function encodeRFC5987ValueChars(str) {
return (
encodeURIComponent(str)
// The following creates the sequences %27 %28 %29 %2A (Note that
// the valid encoding of "*" is %2A, which necessitates calling
// toUpperCase() to properly encode). Although RFC3986 reserves "!",
// RFC5987 does not, so we do not need to escape it.
.replace(
/['()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
)
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
.replace(/%(7C|60|5E)/g, (str, hex) =>
String.fromCharCode(parseInt(hex, 16)),
)
);
}
RFC3986 編碼
較新的 RFC3986 保留了 !、'、(、) 和 *,儘管這些字元沒有正式化的 URI 分隔用途。以下函式將字串編碼為符合 RFC3986 的 URL 元件格式。它還編碼了 [ 和 ],它們是 IPv6 URI 語法的一部分。符合 RFC3986 的 encodeURI 實現不應轉義它們,這在 encodeURI() 示例中有所演示。
function encodeRFC3986URIComponent(str) {
return encodeURIComponent(str).replace(
/[!'()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
);
}
編碼孤立代理會丟擲錯誤
如果嘗試編碼不屬於高低代理對的代理,將丟擲 URIError。例如
// High-low pair OK
encodeURIComponent("\uD800\uDFFF"); // "%F0%90%8F%BF"
// Lone high-surrogate code unit throws "URIError: malformed URI sequence"
encodeURIComponent("\uD800");
// Lone high-surrogate code unit throws "URIError: malformed URI sequence"
encodeURIComponent("\uDFFF");
你可以使用 String.prototype.toWellFormed(),它將孤立代理替換為 Unicode 替換字元 (U+FFFD),以避免此錯誤。你還可以使用 String.prototype.isWellFormed() 在將字串傳遞給 encodeURIComponent() 之前檢查它是否包含孤立代理。
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-encodeuricomponent-uricomponent |
瀏覽器相容性
載入中…