“Unterminated template literal” syntax error when literal contains script tag [duplicate]

*爱你&永不变心* 提交于 2019-11-29 11:00:03

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/36607932/unterminated-template-literal-syntax-error-when-literal-contains-script-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!