title: How do I escape a string inside JavaScript code inside an onClick handler?
body: <p>Maybe I'm just thinking about this too hard, but I'm having a problem figuring out what escaping to use on a string in some JavaScript code inside a link's onClick handler. Example:</p>
  
  <pre><code>&lt;a href="#" onclick="SelectSurveyItem('&lt;%itemid%&gt;', '&lt;%itemname%&gt;'); return false;"&gt;Select&lt;/a&gt;
  </code></pre>
  
  <p>The <code>&lt;%itemid%&gt;</code> and <code>&lt;%itemname%&gt;</code> are where template substitution occurs. My problem is that the item name can contain any character, including single and double quotes. Currently, if it contains single quotes it breaks the JavaScript code.</p>
  
  <p>My first thought was to use the template language's function to JavaScript-escape the item name, which just escapes the quotes. That will not fix the case of the string containing double quotes which breaks the HTML of the link. How is this problem normally addressed? Do I need to HTML-escape the entire onClick handler?</p>
  
  <p>If so, that would look really strange since the template language's escape function for that would also HTMLify the parentheses, quotes, and semicolons...</p>
  
  <p>This link is being generated for every result in a search results page, so creating a separate method inside a JavaScript tag is not possible, because I'd need to generate one per result.</p>
  
  <p>Also, I'm using a templating engine that was home-grown at the company I work for, so toolkit-specific solutions will be of no use to me.</p>