Tuesday, February 17, 2009

Unescaping unicode characters in C# encoded in JavaScript

JavaScript escape and unescape are very powerful functions, but they do have its various idiosyncrasies that do not work appropriately with the standard escaping methods in the serverside C# code.
The regualr methods we have on C# to handle escaping/unescaping are:
  • Uri.EscapeDataString
  • Uri.EscapeUriString
  • HttpUtility.UrlEncode
  • HttpUtility.URLPathEncode
but none of these return a properly unescaped string as escaped by the JavaScript conterpart. Fortunately for us, Microsoft's own JScript libary has it's own, serverside implementation of the JavaScript encode/unencode methods, that do the job exactly as expected. They are exact equivalents.

string Microsoft.JScript.GlobalObject.unescape(string escapedString)

To use it in your code:
  1. Reference Micrtosoft.JScript.dll in your project
  2. Use the static methods in GlobalObject to do the escape/unescape

No comments: