Solve - Unterminated string constant Error in JavaScript


Borislav Hadzhiev

Tue Oct 19 20212 min read


Photo by Mitchell Orr

Solve - Unterminated string constant Error #

The "Unterminated string constant" error occurs for 3 main reasons:

  • You have forgotten the closing quote of a string.
  • You haven't escaped characters in the string correctly.
  • The string is split across multiple lines incorrectly.

unterminated string constant

Here are some examples of when the error occurs.

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

In the first example, we forgot the closing quote of the string.

In the second example, we tried to split a string across multiple lines using double quotes. In this scenario you should use backticks `` instead.

// ✅ 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.
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 also paste your code into an online Syntax Validator. The validator should be able to tell you on which line the error occurs.

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 \.

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.