SyntaxError: string literal contains an unescaped line break

JavaScript 错误“字符串字面量包含未转义的换行符”在某处存在未终止的字符串字面量时发生。字符串字面量必须用单引号 (') 或双引号 (") 括起来,并且不能跨多行拆分。

消息

SyntaxError: Invalid or unexpected token (V8-based)
SyntaxError: '' string literal contains an unescaped line break (Firefox)
SyntaxError: Unexpected EOF (Safari)

错误类型

SyntaxError

哪里出错了?

某处存在未终止的字符串字面量。字符串字面量必须用单引号 (') 或双引号 (") 括起来。JavaScript 对单引号字符串和双引号字符串不作区分。转义序列在用单引号或双引号创建的字符串中都有效。要解决此错误,请检查是否

  • 你的字符串字面量有开引号和闭引号(单引号或双引号),
  • 你已正确转义了你的字符串字面量,
  • 你的字符串字面量没有跨多行拆分。

示例

多行

在 JavaScript 中,你不能像这样将字符串拆分到多行

js
const longString = "This is a very long string which needs
                    to wrap across multiple lines because
                    otherwise my code is unreadable.";
// SyntaxError: unterminated string literal

相反,请使用+ 运算符、反斜杠或模板字面量+ 运算符变体看起来像这样

js
const longString =
  "This is a very long string which needs " +
  "to wrap across multiple lines because " +
  "otherwise my code is unreadable.";

或者,你可以在每行末尾使用反斜杠字符(“\”)来表示字符串将在下一行继续。请确保反斜杠后面没有空格或任何其他字符(除了换行符),或者作为缩进;否则它将不起作用。该形式看起来像这样

js
const longString =
  "This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";

另一种可能性是使用模板字面量

js
const longString = `This is a very long string which needs 
to wrap across multiple lines because 
otherwise my code is unreadable.`;

另见