Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
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: const str = "hello // ๐๏ธ should use backticks instead world"
In the first example, we forgot the closing quote of the string.
// โ added closing quote to string const a = 'test'
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`
Backticks enable us to declare string literals that span multiple lines.
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 !
replace()
method with a regular expression that removes all line breaks and works on all operating systems.To solve the 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 4
.
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.
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.