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: http://www.wwco.com/~wls/blog/2007/04/25/using-script-in-a-javascript-literal/

This is the C# I now have in place:

        // see http://www.wwco.com/~wls/blog/2007/04/25/using-script-in-a-javascript-literal/

        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:

    http://msdn.microsoft.com/en-us/library/system.web.httputility.javascriptstringencode(v=vs.110).aspx

    ??

    ReplyDelete