Tue Oct 19 2021·2 min read
Photo by Mitchell Orr
The "Unterminated string constant" error occurs for 3 main reasons:
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`
const str = 'a\n multi \n line \r string \n!'; const withoutLineBreaks = str.replace(/[\r\n]/gm, ''); console.log(withoutLineBreaks); // 👉️ a multi line string !
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.
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
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.