“未终止的模板文字”文字包含脚本标记时的语法错误 [英] "Unterminated template literal" syntax error when literal contains script tag

查看:336
本文介绍了“未终止的模板文字”文字包含脚本标记时的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ES6模板文字在字符串中构造一些HTML,到目前为止它一直运行良好。但是,只要我尝试将字面文本< / script> 放入我的字符串中,浏览器就会抛出并抛出语法错误:

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

这是一个简单的JavaScript示例,它会抛出错误:

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)

请参阅 JS Fiddle <中的上述代码/ a>。

See the above code in JS Fiddle.

看来发生的事情是,它放弃了寻找最终文字引用,而是开始将所有内容视为文字HTML,所以所有的在该点之后的JavaScript被错误地视为HTML,它不是!

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!

如果我用脚本 >任何其他合法的HTML标记(甚至无效的标签,如 scripty )然后它工作正常,所以我看不出这可能是一种语法错误或奇怪的情况,我认为我键入了一个字符(例如反引号),而是键入了另一个看起来几乎像它。

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.

我字面意思是创建一个字符串(根据我的理解,在编译时),浏览器应该尝试t将其作为HTML或以任何方式解析它。那么是什么给出了?

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?

推荐答案

如果你插入< / script> 在脚本标记内部,无论它是引号,撇号还是模板文字中的字符串,它都始终关闭脚本标记。你必须逃避它,例如:

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)

但是,如果您使用外部脚本< script src =url>< / script> ,它应该可以正常工作而不会转义。

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

这篇关于“未终止的模板文字”文字包含脚本标记时的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆