why escaping / in javascript '<\\/script>'?

匿名 (未验证) 提交于 2019-12-03 08:51:18

问题:

I have seen everyone doing it tho i dont' get why.

document.write('<script src="src"><\/script>'); 

I mean using the single ' you shouldn't need to esacape chars?

回答1:

  1. Single and double quoted strings have the same escaping rules.
  2. It prevents </script> from being parsed as an closing tag.

"</script> and "<\/script>" are the same to JavaScript, but only the first one is interpreted by the HTML parser to contain a HTML closing tag.



回答2:

</script> always ends a script block - no matter what (e.g. HTML comments or CDATA) you do. So it must never occur in a script block unless you actually want to end the block and the easiest way to do so is escaping forward slashes (the escaping doesn't do anything; in JavaScript unknown escape sequences just "lose" their backslash).



回答3:

The HTML-parser will see the </script> in your string as a closing tag and close your initial <script>. It does not have the concept of strings.

So your piece of JavaScript will only be seen as document.write('<script src="src"> if you dont escape it and the rest, '); will be seen as a HTML text-node.

Also, note that you don't have to "escape" the </script> in a particular way. As long as you don't write it exactly like </script>, anything is ok. Some examples that all work:

document.write('<script src="src"><\/script>'); document.write('<script src="src"></scr' + 'ipt>'); document.write('<script src="src"></' + 'script>'); 


回答4:

It's for an XHTML validity. You can use a validator for see that : http://validator.w3.org/. You can use a also use CDATA tag. See this similar question for more details : Escaping HTML in jQuery so it's valid



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