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 |
浏览器兼容性
加载中…