tag in a JavaScript variable?", "text": "<p>I have a string in Javascript where I have to escape several characters:</p>\n\n<pre class="prettyprint"><code><script>\nfunction GenerateCode() {\n alert(ctry);\n var script = "<script async src=\\"//somesite.com/feed/livetrend.js\\"></script>";\n}\n</script>\n</code></pre>\n\n<p>I have tried the following to escape the characters:</p>\n\n<pre class="prettyprint"><code>var script = "<script async src=\\"//somesite.com/feed/livetrend.js\\"></script>";\n</code></pre>\n\n<p>However, this does not work correctly, despite having taken care of including an escape character <code>\\</code> in front of <code>"</code> </p>\n\n<p>It an error -<code>unterminated string constant</code>.</p>", "answerCount": 1, "upvoteCount": 464, "dateCreated": "2015-02-21 07:19:27", "dateModified": "2022-10-12 14:28:27", "author": { "type": "Person", "name": "m Raj" }, "acceptedAnswer": { "@type": "Answer", "text": "<p>The issue is that when the browser encounters the closing <code></script></code> tag inside a open <code><script></code> 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.</p>\n\n<h3>Option 1 - Escape the <code>/</code> in the closing <code>script</code> tag:</h3>\n\n<pre class="prettyprint"><code>var script = '<script async src="//somesite.com/feed/livetrend.js"><\\/script>';\n</code></pre>\n\n<h3>Option 2 - Wrap the JavaScript in commented out HTML comments:</h3>\n\n<pre class="prettyprint"><code><script>\n/*<!--*/\nvar script = '<script async src="//somesite.com/feed/livetrend.js"></script>';\n/*-->*/\n</script>\n</code></pre>\n\n<h3>Option 3 - Put the JavaScript into an external file:</h3>\n\n<p>Of course, moving the JavaScript into an external file will avoid this issue altogether, though it might not be preferable.</p>", "upvoteCount": 197, "url": "https://exchangetuts.com/how-to-include-an-escapedscript-script-tag-in-a-javascript-variable-1639910230760402#answer-1649107638349815", "dateCreated": "2022-10-11 01:28:27", "dateModified": "2022-10-12 14:28:27", "author": { "type": "Person", "name": "Alexander O'Mara" } } } }