SyntaxError: unterminated string literal - JavaScript 编辑

The JavaScript error "unterminated string literal" occurs when there is an unterminated String somewhere. String literals must be enclosed by single (') or double (") quotes.

Message

SyntaxError: Unterminated string constant (Edge)
SyntaxError: unterminated string literal (Firefox)

Error type

SyntaxError

What went wrong?

There is an unterminated String 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:

  • you have opening and closing quotes (single or double) for your string literal,
  • you have escaped your string literal correctly,
  • your string literal isn't split across multiple lines.

Examples

Multiple lines

You can't split a string across multiple lines like this in JavaScript:

var 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:

var 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:

var 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, which are supported in ECMAScript 2015 environments:

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

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:86 次

字数:4004

最后编辑:7 年前

编辑次数:0 次

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文