大网数据广告活动
Web 标准与前端开发

SyntaxError: character class escape cannot be used in class range in regular expression

· 52CE 我爱测

The JavaScript exception "character class escape cannot be used in class range in regular expression" occurs when a Unicode-aware regular expression pattern contains a character class where a boundary of a character range is another character class, such as a character class esca

The JavaScript exception "character class escape cannot be used in class range in regular expression" occurs when a Unicode-aware regular expression pattern contains a character class where a boundary of a character range is another character class, such as a character class escape.

Message

SyntaxError: Invalid regular expression: /[\s-1]/u: Invalid character class (V8-based)
SyntaxError: character class escape cannot be used in class range in regular expression (Firefox)
SyntaxError: Invalid regular expression: invalid range in character class for Unicode pattern (Safari)

Error type

SyntaxError

What went wrong?

A character class can specify a range of characters by using a hyphen (-) between two characters. For example, [a-z] matches any lowercase letter from a to z. The two bounds of the range must represent single characters in order for the range to make sense. If one of the bounds actually represents multiple characters, an error is generated. In non-v-mode character classes, only character class escapes are allowed inside character classes; in v-mode character classes, this can also happen if one the bounds is another [...] character class.

In Unicode-unaware mode, this syntax causes the - to become a literal character instead of generating an error, but this is a deprecated syntax and you should not rely on it.

Examples

Invalid cases

/[\s-_]/u; // \s is a character class escape for whitespace
/[A-\D]/u; // \D is a character class escape for non-digits
/[\p{L}-\p{N}]/u; // \p{L} is a character class escape for Unicode letters
/[[A-z]-_]/v; // In unicodeSets mode, character classes can be nested

Valid cases

// Put the hyphen at the start of the character class,
// so it matches the literal character
/[-\s_]/u;
// Escape the hyphen so it also matches the literal character
/[\s\-_]/u;
// Remove the backslash so the bound is a literal character
/[A-D]/u;
// Remove the hyphen so the two bounds represent two alternatives
/[\p{L}\p{N}]/u;
// Use -- in unicodeSets mode, which represents set subtraction
/[[A-z]--_]/v;

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。