String.prototype.isWellFormed()

String 值的 isWellFormed() 方法返回一个布尔值,指示该字符串是否包含任何 孤独的代理

¥The isWellFormed() method of String values returns a boolean indicating whether this string contains any lone surrogates.

语法

¥Syntax

js
isWellFormed()

参数

¥Parameters

没有任何。

¥None.

返回值

¥Return value

如果此字符串不包含任何单独代理,则返回 true,否则返回 false

¥Returns true if this string does not contain any lone surrogates, false otherwise.

描述

¥Description

JavaScript 中的字符串采用 UTF-16 编码。UTF-16 编码有代理对的概念,在 UTF-16 字符、Unicode 代码点和字素簇 章节中有详细介绍。

¥Strings in JavaScript are UTF-16 encoded. UTF-16 encoding has the concept of surrogate pairs, which is introduced in detail in the UTF-16 characters, Unicode code points, and grapheme clusters section.

isWellFormed() 允许你测试字符串是否格式良好(即不包含任何单独的代理)。与自定义实现相比,isWellFormed() 更高效,因为引擎可以直接访问字符串的内部表示。如果需要将字符串转换为格式正确的字符串,请使用 toWellFormed() 方法。isWellFormed() 允许你以与格式正确的字符串不同的方式处理格式错误的字符串,例如抛出错误或将其标记为无效。

¥isWellFormed() allows you to test whether a string is well-formed (i.e. does not contain any lone surrogates). Compared to a custom implementation, isWellFormed() is more efficient, as engines can directly access the internal representation of strings. If you need to convert a string to a well-formed string, use the toWellFormed() method. isWellFormed() allows you to handle ill-formed strings differently from well-formed strings, such as throwing an error or marking it as invalid.

示例

¥Examples

使用 isWellFormed()

¥Using 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()中的错误

¥Avoiding errors in encodeURI()

如果传递的字符串格式不正确,encodeURI 会抛出错误。通过在将字符串传递给 encodeURI() 之前使用 isWellFormed() 测试字符串可以避免这种情况。

¥encodeURI throws an error if the string passed is not well-formed. This can be avoided by using isWellFormed() to test the string before passing it to encodeURI().

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.
}

规范

Specification
ECMAScript Language Specification
# sec-string.prototype.iswellformed

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看