Is it possible to correctly escape arbitrary script tag contents?
<p>Question about ETAGO - end-tag open: Given a string, is it possible to safely escape it in a generic way for insertion into a sprintf style template like:</p>

<pre class="lang-none prettyprint-override"><code>&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;tag demo&lt;/title&gt;
    &lt;script type="%s"&gt;
%s
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>I've seen <a href="https://mathiasbynens.be/notes/etago" rel="nofollow noreferrer">descriptions</a> that show how to escape various specific strings, but nothing generic.</p>

<p>Is it really true that such escaping is impossible in a generic way?</p>

<p>Here are some edge cases:</p>

<pre class="lang-none prettyprint-override"><code>&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;tag demo&lt;/title&gt;
    &lt;script type="text/javascript"&gt;
        var endtag = "&lt;/a&gt;";
        // OK, this is weird - but valid!
        var lessthan = 42 &lt; /script/;
        console.log (endtag, lessthan, '&lt;'.match(/&lt;/));
        // The next two lines are weird - and cause invalid HTML
        // &lt;/script&gt;
        var lessthan2 = 42 &lt;/script/;
        // Is this still being run?
        console.log ("still here");
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>This is not valid HTML since the <code>&lt;/script</code> sequence is found inside the script tag's "weird" lines. If I move the inner HTML from the script tag to an external .js file, <code>still here</code> gets logged to the console, and I believe it to be valid javascript, just not valid HTML when inside a script tag. Is there some safe generic way to escape a javascript (or css? or <code>type="foo/bar"</code>?) string for insertion into a script tag?</p>