语法错误:字符串字面量包含未转义的换行符
当某个地方存在未终止的字符串字面量时,就会发生 JavaScript 错误“字符串字面量包含未转义的换行符”。字符串字面量必须用单引号 ('
) 或双引号 ("
) 括起来,并且不能跨多行。
消息
SyntaxError: Invalid or unexpected token (V8-based) SyntaxError: '' string literal contains an unescaped line break (Firefox) SyntaxError: Unexpected EOF (Safari)
错误类型
出了什么问题?
示例
多行
在 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.`;