语法错误:字符串文字包含未转义的换行符
当某处存在未终止的 字符串字面量 时,就会发生 JavaScript 错误 "字符串文字包含未转义的换行符"。字符串文字必须用单引号 ('
) 或双引号 ("
) 括起来,并且不能跨多行拆分。
¥The JavaScript error "string literal contains an unescaped line break" occurs when there is an unterminated
string literal somewhere. String literals must be enclosed by single
('
) or double ("
) quotes and cannot split across multiple lines.
信息
错误类型
什么地方出了错?
¥What went wrong?
某处有一个未终止的 字符串字面量。字符串文字必须用单引号 ('
) 或双引号 ("
) 括起来。JavaScript 不区分单引号字符串和双引号字符串。转义序列 适用于使用单引号或双引号创建的字符串。要修复此错误,请检查是否:
¥There is an unterminated
string literal somewhere. String literals must be
enclosed by single ('
) or double ("
) quotes. JavaScript makes
no distinction between single-quoted strings and double-quoted strings.
Escape sequences work
in strings created with either single or double quotes.
To fix this error, check if:
- 你的字符串文字有左引号和右引号(单引号或双引号),
- 你已正确转义字符串文字,
- 你的字符串文字不会分成多行。
示例
多条线路
¥Multiple lines
在 JavaScript 中,你不能像这样将字符串拆分为多行:
¥You can't split a string across multiple lines like this in JavaScript:
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
请改用 * 运算符、反斜杠或 模板文字。+
运算符变体如下所示:
¥Instead, use the + operator,
a backslash, or template literals.
The +
operator variant looks like this:
const longString =
"This is a very long string which needs " +
"to wrap across multiple lines because " +
"otherwise my code is unreadable.";
或者,你可以在每行末尾使用反斜杠字符 ("") 来指示该字符串将在下一行继续。确保反斜杠后面没有空格或任何其他字符(换行符除外),也没有作为缩进;否则它将无法工作。该表格如下所示:
¥Or you can use the backslash character ("") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:
const longString =
"This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";
另一种可能性是使用 模板文字。
¥Another possibility is to use template literals.
const longString = `This is a very long string which needs
to wrap across multiple lines because
otherwise my code is unreadable.`;