title: Is it necessary to "escape" character "<" and ">" for javascript string?
body: <p>Sometimes, server side will generate strings to be embedded in inline JavaScript code. For example, if "UserName" should be generated by ASP.NET. Then it looks like.</p>
  
  <pre><code>&lt;script&gt;
     var username = "&lt;%UserName%&gt;";
  &lt;/script&gt;
  </code></pre>
  
  <p>This is not safe, because a user can have his/her name to be </p>
  
  <p><code>&lt;/script&gt;&lt;script&gt;alert('bug')&lt;/script&gt;&lt;/script&gt;</code></p>
  
  <p>It is XSS vulnerability.</p>
  
  <p>So, basically, the code should be:</p>
  
  <pre><code>&lt;script&gt;
     var username = "&lt;% JavascriptEncode(UserName)%&gt;";
  &lt;/script&gt;
  </code></pre>
  
  <p>What <strong>JavascriptEncode</strong> does is to add charater "\" before "/" and "'" and """. So, the output html is like.
      
         var username = "&lt;/script>alert(\'bug\')&lt;/script>&lt;/script>";
      </p>
  
  <p>Browser will not interpret "<strong><em>&lt;/script></em></strong>" as end of script block. So, XSS in avoided.</p>
  
  <p>However, there are still "&lt;" and ">" there. It is suggested to escape these two characters as well. First of all, I don't believe it is a good idea to change "&lt;" to "&amp;lt;" and ">" to "&amp;gt;" here. And, I'm not sure changing "&lt;" to "\&lt;" and ">" to "\>" is recognizable to all browsers. It seems it is not necessary to do further encoding for "&lt;" and ">".</p>
  
  <p>Is there any suggestion on this?</p>
  
  <p>Thanks.</p>