Thursday, December 18, 2008

Escaping javascript strings

I wanted to write out javascript string literals as safely as I could. The only problem being special characters - e.g. ', <, >, etc.

I used this blog post as a base:

This is the C# I now have in place:

        // see

        private static String EscapeJavascriptStringLiteralPlease(String str)


          str = str.Replace("\\","\\\\"); // escape single backslashes

          str = str.Replace("'","\\'"); // escape single quotes

          str = str.Replace("\"","\\\""); // escape double quotes

          str = str.Replace("<","\\<"); // escape open angle bracket

          str = str.Replace(">","\\>"); // escape close angle bracket

          return str;


But was there a way I could have done this straight from the standard ASP.Net libraries?

1 comment:

  1. HttpUtility.JavaScriptStringEncode Method: