SyntaxError:JavaScript 中未终止的字符串常量

SyntaxError: JavaScript 中未终止的字符串常量

SyntaxError: Unterminated string constant in JavaScript

“Unterminated string constant”错误的发生有 3 个主要原因:

  • 您忘记了字符串的结束引号。
  • 您没有正确转义字符串中的字符。
  • 字符串被错误地分割成多行。

未终止的字符串常量

以下是错误发生时间的一些示例。

索引.js
// ⛔️ SyntaxError: Unterminated string constant const a = 'test // 👈️ forgot closing quote // ⛔️ SyntaxError: Unterminated string constant const str = "hello // 👈️ should use backticks instead world"

在第一个例子中,我们忘记了字符串的结束引号。

在第二个示例中,我们尝试使用双引号将字符串拆分为多行。在这种情况下,您应该改用反引号 “。

索引.js
// ✅ works const str = `hello world`
If you are fetching a string from a server or getting one from user input, you can remove the newline characters to make sure the string is valid. Here’s how you can remove the line breaks from a string.
index.js
const str = 'a\n multi \n line \r string \n!'; const withoutLineBreaks = str.replace(/[\r\n]/gm, ''); console.log(withoutLineBreaks); // 👉️ a multi line string !
We used the replace() method with a regular expression that removes all line breaks and works on all operating systems.

To solve the “Unterminated string constant” error, make sure to enclose your
strings in quotes consistently.

String literals must be enclosed in single quotes, double quotes or backticks.
When writing a multiline string use backticks.

If you have difficulty finding where the error occurred, open your browser’s console or your terminal if you’re using Node.js.

The error will show the file name and the line the error occurred on, e.g.
index.js:4 means that the error occurred in the index.js file on line 4.

You can paste your code into an online Syntax Validator . The validator should be able to tell you on which line the error occurred.

You can hover over the squiggly red line to get additional information.

If you have to escape characters in a string, you can use a backslash \.

index.js
const a = 'it\'s there';

An alternative and even better approach is to use backticks or double quotes to
enclose the string, then you wouldn’t have to escape the single quote.

Conclusion #

To solve the “Unterminated string constant” error, make sure to enclose your
strings in quotes consistently.

字符串文字必须用单引号、双引号或反引号括起来。编写多行字符串时使用反引号。