Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

Programatically escape / script closing tag in javascript

I have this variable which contains a script html code

<script>
var script = "<script>console.log('script here')</script>"
</script>

how do we programmatically escape the / in the closing tag </script> so it will look like the code below

<script>
var script = "<script>console.log('script here')</script>"
</script>
question from:https://stackoverflow.com/questions/65944545/programatically-escape-script-closing-tag-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It does not work as you think.

The first fragment of code does not work because the browser finds the </script> piece in the string and thinks that it is the closing tag of the script element. It treats the rest of the script and the real </script> closing tag as regular text and displays it in the page (except for the </script> tag).

This means that only a fragment of your script is parsed, the parser finds a syntax error in it (the string is not closed) and the script does not run.

There is no way to fix this using JavaScript code. It is not a coding problem. It is an HTML problem (kind of) and its only solution is to write the HTML in a way that avoids the issue.

The HTML document contains a closing tag </script> inside the body of a script element. For normal HTML content (a paragraph, for example) the solution is straight forward: use &lt; and &gt; to encode < and >:

<p> This is a paragraph that contains a &lt;p&gt; closing tag</p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...