String.prototype.toWellFormed()
String 值的 toWellFormed() 方法會返回一個字串,該字串中所有獨立的代理單元(lone surrogates)都已替換為 Unicode 替換字元 U+FFFD。
語法
js
toWellFormed()
引數
無。
返回值
一個新字串,它是此字串的副本,其中所有獨立的代理單元都已替換為 Unicode 替換字元 U+FFFD。如果 str 格式良好,仍然會返回一個新字串(本質上是 str 的副本)。
描述
JavaScript 中的字串是 UTF-16 編碼的。UTF-16 編碼包含代理對(surrogate pairs)的概念,這在UTF-16 字元、Unicode 程式碼點和圖形簇部分有詳細介紹。
toWellFormed() 會遍歷此字串的程式碼單元,並將任何獨立的代理單元替換為 Unicode 替換字元 U+FFFD �。這確保了返回的字串格式良好,並且可以在需要格式良好字串的函式中使用,例如 encodeURI。與自定義實現相比,toWellFormed() 更高效,因為引擎可以直接訪問字串的內部表示。
當非格式良好的字串在某些上下文中(例如 TextEncoder)使用時,它們會自動使用相同的替換字元轉換為格式良好的字串。當獨立的代理單元被渲染時,它們也會被渲染為替換字元(一個帶有問號的菱形)。
示例
使用 toWellFormed()
js
const strings = [
// Lone leading surrogate
"ab\uD800",
"ab\uD800c",
// Lone trailing surrogate
"\uDFFFab",
"c\uDFFFab",
// Well-formed
"abc",
"ab\uD83D\uDE04c",
];
for (const str of strings) {
console.log(str.toWellFormed());
}
// Logs:
// "ab�"
// "ab�c"
// "�ab"
// "c�ab"
// "abc"
// "ab😄c"
避免 encodeURI() 中的錯誤
encodeURI 如果傳入的字串格式不正確,則會丟擲錯誤。透過先使用 toWellFormed() 將字串轉換為格式良好的字串,可以避免這種情況。
js
const illFormed = "https://example.com/search?q=\uD800";
try {
encodeURI(illFormed);
} catch (e) {
console.log(e); // URIError: URI malformed
}
console.log(encodeURI(illFormed.toWellFormed())); // "https://example.com/search?q=%EF%BF%BD"
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-string.prototype.towellformed |
瀏覽器相容性
載入中…