String.prototype.isWellFormed()
String 值的 isWellFormed() 方法返回一個布林值,指示此字串是否包含任何單獨的代理(lone surrogates)。
語法
js
isWellFormed()
引數
無。
返回值
如果此字串不包含任何單獨的代理,則返回 true,否則返回 false。
描述
JavaScript 中的字串是 UTF-16 編碼的。UTF-16 編碼有一個代理對(surrogate pairs)的概念,這在UTF-16 字元、Unicode 碼點和字形簇部分有詳細介紹。
isWellFormed() 允許您測試一個字串是否格式良好(即,不包含任何單獨的代理)。與自定義實現相比,isWellFormed() 更高效,因為引擎可以直接訪問字串的內部表示。如果您需要將字串轉換為格式良好的字串,請使用 toWellFormed() 方法。isWellFormed() 允許您以不同於格式良好的字串的方式處理格式不正確的字串,例如丟擲錯誤或將其標記為無效。
示例
使用 isWellFormed()
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.isWellFormed());
}
// Logs:
// false
// false
// false
// false
// true
// true
避免 encodeURI() 中的錯誤
encodeURI 如果傳入的字串格式不正確,則會丟擲錯誤。透過在將字串傳遞給 encodeURI() 之前使用 isWellFormed() 進行測試,可以避免這種情況。
js
const illFormed = "https://example.com/search?q=\uD800";
try {
encodeURI(illFormed);
} catch (e) {
console.log(e); // URIError: URI malformed
}
if (illFormed.isWellFormed()) {
console.log(encodeURI(illFormed));
} else {
console.warn("Ill-formed strings encountered."); // Ill-formed strings encountered.
}
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-string.prototype.iswellformed |
瀏覽器相容性
載入中…