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.

1
  • Post the actual string you are trying to escape.
    – Rahul
    Aug 20, 2015 at 19:52

1 Answer 1

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")
1
  • 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. stackoverflow.com/questions/20477063/…
    – Tonkleton
    Aug 20, 2015 at 20:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.