Unterminated string literal error with the script and style tags

Published: · Reading time: 1 min

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.

Unterminated string literal error
Unterminated string literal error

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.

Unterminated string literal error in Chrome
Chrome console error
Unterminated string literal error in Firefox
Firefox console error

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.

  1. Escape the closing tag slash:
    var str = "<script><\/script>";
    
  2. Split the string:
    var str = "<script>" + "</script>";
    
  3. Use template literals:
    var str = `<script></script>`;
    
Like this article? Share it on: