SyntaxError: invalid decimal escape in regular expression

JavaScript 异常 "invalid decimal escape in regular expression"(正则表达式中无效的十进制转义序列)发生在 支持 Unicode 的正则表达式模式中使用传统的八进制转义序列时。

消息

SyntaxError: Invalid regular expression: /\00/u: Invalid decimal escape (V8-based)
SyntaxError: invalid decimal escape in regular expression (Firefox)
SyntaxError: Invalid regular expression: invalid octal escape for Unicode pattern (Safari)

错误类型

SyntaxError

哪里出错了?

在正则表达式中,\0 后面跟着另一个数字是传统的八进制转义序列。在模板字符串和严格模式的字符串字面量中禁止使用相同的语法。在正则表达式中,Unicode 感知模式(uv)会禁用此特性。\0 跟着另一个数字是有效的转义序列,表示空字符(U+0000)。

\ 后面跟着一个非零数字是反向引用,如果它没有引用捕获组,则在 Unicode 感知模式下是无效的;更多信息请参见无效的标识转义

示例

无效案例

js
/\00/u;
/\01/u;

有效情况

js
// If you want to match NULL followed by a digit, use a character class
/[\0]0/u;
// If you want to match a character by its character value, use \x
/\x01/u;

另见