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)

另見