Solve - Unterminated string constant Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

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.

index.js
// โ›”๏ธ 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.

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

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee