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

SyntaxError: \\ at end of pattern

· 52CE 我爱测

The JavaScript exception "\ at end of pattern" occurs when a regular expression pattern ends with an unescaped backslash (`\`). In a regex literal, the backslash would cause the closing slash `/` to be a literal character, so this can only appear when using the RegExp/RegExp cons

The JavaScript exception "\ at end of pattern" occurs when a regular expression pattern ends with an unescaped backslash (\). In a regex literal, the backslash would cause the closing slash / to be a literal character, so this can only appear when using the RegExp/RegExp constructor.

Message

SyntaxError: Invalid regular expression: /\/: \ at end of pattern (V8-based)
SyntaxError: \ at end of pattern (Firefox)
SyntaxError: Invalid regular expression: \ at end of pattern (Safari)

Error type

SyntaxError

What went wrong?

A backslash cannot appear literally in a regular expression. It either precedes another character to escape it, or is itself escaped by another backslash. A backslash at the end of a regular expression pattern is invalid because it is not escaping anything.

Examples

Double-escaping backslashes

This error can only happen when using the RegExp() constructor. Consider the following code, which intends to match a single backslash character:

const pattern = new RegExp("\\");

In JavaScript strings, backslashes are also escape sequences. Therefore, the two backslashes in the string literal "\\" are interpreted as a single backslash. The RegExp() constructor then only sees a single backslash character in the regex source. To fix this, you need to double-escape the backslash:

const pattern = new RegExp("\\\\");

The four backslashes in the string literal represent two backslashes in the regex source, which then becomes a character escape for a single backslash literal character.

See also

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

资料来源与适用范围

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

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

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