Unterminated string literal error with the script and style tags
I recently encountered an Unterminated string literal
error, which turned out to be totally unexpected for me, as the string looked completely fine to me.
Usually, the Unterminated string literal
error occurs when the string is not enclosed inside the single ('
) or double ("
) quotes.
In my case, the string looked as follows:
var str = "<script></script>";
Immediately I was notified by the code editor that there was an issue with this string.
Since I’ve ensured that the string was closed by the double quote, I was confused a bit, to say the least.
I’ve tried both single and double quotes. But the error was still there, and the console was saying the same. However, Firefox was more precise.
But after some investigation, I’ve found out that the script
and style
tags inside a string should be treated like HTML, hence the error.
There are a few ways to fix that.
- Escape the closing tag slash:
var str = "<script><\/script>";
- Split the string:
var str = "<script>" + "</script>";
- Use template literals:
var str = `<script></script>`;