Michael Michael -4 years ago 212
HTML Question

"Unterminated template literal" syntax error when literal contains script tag

I'm using ES6 template literals to construct some HTML in strings, and so far it has been working fine. However, as soon as I try to put the literal text

</script>
in my string the browser throws up and throws the syntax error:

SyntaxError: Unterminated template literal


Here is a simple JavaScript sample which throws the error:

var str=`
<script>
</script>
`
var pre = document.createElement('pre')
pre.textContent = str
document.body.appendChild(pre)


See the above code in JS Fiddle.

It appears that what is happening is that it gives up looking for the end literal quote and instead starts treating everything at point as literal HTML, so all the JavaScript after that point is incorrectly treated as HTML, which it is not!

If I replace
script
by any other legal HTML tag (and even invalid tags like
scripty
) then it works just fine, so I can't see how this can possibly be a syntax error or a weird case where I think I have typed one character (e.g. the backtick) but instead have typed another that looks almost like it.

I am literally creating a string (to my understand, at compile time), the browser should not be attempting to treat it as HTML or in any way parse it. So what gives?

Answer Source

If you insert </script> inside a script tag, no matter if it's a string in quotes, apostrophes, or even a template literal, it will always close the script tag. You have to escape it, for example like that:

var str=`
<script>
<\/script>
`
var pre = document.createElement('pre')
pre.textContent = str
document.body.appendChild(pre)

However, if you use external script <script src="url"></script>, it should work fine without escaping.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download