SyntaxError: invalid unicode escape in regular expression

\c\u 字符转义后面没有跟着有效字符时,会发生 JavaScript 异常“invalid unicode escape in regular expression”(正则表达式中存在无效的 Unicode 转义)。

消息

SyntaxError: Invalid regular expression: /\u{123456}/u: Invalid Unicode escape (V8-based)
SyntaxError: invalid unicode escape in regular expression (Firefox)
SyntaxError: Invalid regular expression: invalid Unicode code point \u{} escape (Safari)

错误类型

SyntaxError

哪里出错了?

Unicode 感知模式下,\c 转义序列后面必须跟着一个从 AZaz 的字母,而 \u 转义序列后面必须跟着 4 个十六进制数字,或者 1 到 6 个用花括号 ({}) 括起来的十六进制数字。此外,当使用 \u{xxx} 转义序列时,这些数字必须表示一个有效的 Unicode 码点,这意味着它的值不能超过 10FFFF

示例

无效案例

js
/\u{123456}/u; // Unicode code point is too large
/\u65/u; // Not enough digits
/\c1/u; // Not a letter

有效情况

js
/\u0065/u; // Lowercase "e"
/\u{1f600}/u; // Grinning face emoji
/\cA/u; // U+0001 (Start of Heading)

另见