title: Escaping HTML entities in JavaScript string literals within the <script> block
body: <p>On the one hand if I have</p>
  
  <pre><code>&lt;script&gt;
  var s = 'Hello &lt;/script&gt;';
  console.log(s);
  &lt;/script&gt;
  </code></pre>
  
  <p>the browser will terminate the <code>&lt;script&gt;</code> block early and basically I get the page screwed up. </p>
  
  <p>On the other hand, the value of the string may come from a user (say, via a previously submitted form, and now the string ends up being inserted into a <code>&lt;script&gt;</code> block as a literal), so you can expect anything in that string, including maliciously formed tags. Now, if I escape the string literal with htmlentities() when generating the page, the value of s will contain the escaped entities literally, i.e. s will output</p>
  
  <pre><code>Hello &amp;lt;/script&amp;gt;
  </code></pre>
  
  <p>which is not desired behavior in this case.</p>
  
  <p>One way of properly escaping JS strings within a <code>&lt;script&gt;</code> block is escaping the slash if it follows the left angle bracket, or just always escaping the slash, i.e.</p>
  
  <pre><code>var s = 'Hello &lt;\/script&gt;';
  </code></pre>
  
  <p>This seems to be working fine.</p>
  
  <p>Then comes the question of JS code within HTML event handlers, which can be easily broken too, e.g.</p>
  
  <pre><code>&lt;div onClick="alert('Hello "&gt;')"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>looks valid at first but breaks in most (or all?) browsers. This, obviously requires the full HTML entity encoding.</p>
  
  <p>My question is: what is the best/standard practice for properly covering all the situations above - i.e. JS within a script block, JS within event handlers - if your JS code can partly be generated on the server side and can potentially contain malicious data?</p>