4

I have a string in C# that contains an error message. This message could contain single quotes or double quotes or both, but I am free to manipulate the string however I need (as well as the HTML/Javascript).

For example, the following messages could be displayed (content isn't important, just the fact they could contain single or double quotes):

  • The following error has occurred: "You dun goofed."
  • The specified path isn't valid.
  • The following error has occurred: "I'm a goof"

This string is inserted into HTML as an alert inside of an onClick handler. That sounds complicated so let me show what I mean:

<a onClick="alert('myContentGoesHere')">View Error</a>

I'm able to get the single quotes to display by replacing ' with \' in C#. However, my attempts to similarly escape " has resulted in an odd number of backslashes which terminates the onClick attribute and causes invalid HTML.

So far I have tried to replace " with:

  • \"
  • \\"
  • &quot;
  • &#92;&quot;

No dice. I feel like I might be approaching this from the wrong angle so if you have a solution which goes beyond a string replace, I'm all ears. Thanks for any help you can offer.

Tonkleton
  • 547
  • 3
  • 14

1 Answers1

7

To make the value work as a string literal in JavaScript you need to escape the string delimiter and backslashes. Then you need to HTML encode the JavaScript so that it works as a value in the HTML attribute.

Example:

string code =
  "<a onClick=\"" +
  HttpUtility.HtmlEncode(
    "alert('" +
    myContentGoesHere.Replace("'", "\\'").Replace("\\", "\\\\") +
    "');"
  ) +
  "\">View Error</a>";

If the string can contain control characters, you would need to replace them too. Add the ones that you need from:

 .Replace("\r", "\\r")
 .Replace("\n", "\\n")
 .Replace("\b", "\\b")
 .Replace("\t", "\\t")
 .Replace("\v", "\\v")
 .Replace("\f", "\\f")
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Thank you for the response. This is a fine answer but has made me realize my question was insufficient. There are added layers in my project between the C# and HTML that I originally didn't think were involved: a Kendo template in an ASP.NET view. This seems to "help" by taking your nicely escaped `\"` and turn it into `\\"` for you. However, this led me to an answer than helped me so your answer is good for my question as is. http://stackoverflow.com/questions/20477063/javascript-how-to-escape-double-and-single-quotes-on-kendo-template – Tonkleton Aug 20 '15 at 20:18