How to include an escaped<script> </script> tag in a JavaScript variable?
javascript
Solution
The issue is that when the browser encounters the closing `</script>` tag inside a open `<script>` tag, regardless of the context in which it is used, it will terminate the script tag there. There are a couple of way to avoid this.
Option 1 - Escape the `/` in the closing `script` tag:
var script = '<script async src="//somesite.com/feed/livetrend.js"><\/script>';
Option 2 - Wrap the JavaScript in commented out HTML comments:
<script>
/*<!--*/
var script = '<script async src="//somesite.com/feed/livetrend.js"></script>';
/*-->*/
</script>
Using `<![CDATA[` and `]]>` instead of `<!--` and `-->` also works.
One potential downside to this might be if you also want to have JavaScript strings that also contain these closing comments or CDATA, then it may not work.
Option 3 - Put the JavaScript into an external file:
Of course, moving the JavaScript into an external file will avoid this issue altogether, though it might not be preferable.
Problem
I have a string in Javascript where I have to escape several characters: ``` <script> function GenerateCode() { alert(ctry); var script = "<script async src=\"//somesite.com/feed/livetrend.js\"></script>"; } </script> ``` I have tried the following to escape the characters: ``` var script = "<script async src=\"//somesite.com/feed/livetrend.js\"></script>"; ``` However, this does not work correctly, despite having taken care of including an escape character `\` in front of `"` It an error -`unterminated string constant`.