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.`;