Wednesday, January 23, 2008

C#: Equivalent of JavaScript escape function

Although Uri.EscapeDataString, Uri.EscapeUriString, HttpUtility.UrlEncode and HttpUtility.UrlPathEncode are available to use in C# out of the box, they can not convert all the characters exactly the same way as JavaScript escape function does. For example let's say original string is: "KC's trick /Hello". Then,

Uri.EscapeDataString("KC's trick /Hello") gives:
"KC's%20trick%20%2FHello"
Uri.EscapeUriString("KC's trick /Hello") gives:
"KC's%20trick%20/Hello"
System.Web.HttpUtility.UrlEncode("KC's trick /Hello") gives:
"KC's+trick+%2fHello"
System.Web.HttpUtility.UrlPathEncode("KC's trick /Hello") gives:
"KC's%20trick%20/Hello"

Hence the full proof solution is to use the JScript.Net's own implementation. In order to do that here's what you need to use:

1. Reference Microsoft.JScript.dll in the project reference
2. Use Microsoft.JScript.GlobalObject.escape function to do the encode.

So finally Microsoft.JScript.GlobalObject.escape("KC's trick /Hello") gives:
"KC%27s%20trick%20/Hello"

Similarly to unescape, use Microsoft.JScript.GlobalObject.unescape function. So Microsoft.JScript.GlobalObject.unescape("KC%27s%20trick%20/Hello") gives back:
"KC's trick /Hello"

22 comments:

  1. I think it is a good trick to mimic escape()'s functionality.

    But we cannot use escape() for URI Encoding, right? It will encode "'" single quote, which is not a URI special character, and instead NOT Encode '/', which is a URI special character. So, escape() used directly will not help. URLEncode() may be better for that purpose...

    ReplyDelete
  2. Paddu, thanks for your comment. You're absolutely correct - each function has its own usage, advantages and disadvantages. The reason for this post was that there are lots of methods readily available to encode URI's but none of them convert the "'". That little character causes lot of trouble while replicating a JavaScript popup or window.open call from C# with a "'" in the query string. Only the escape() function in JavaScript handles that and that's why I was looking for an equivalent in C#.

    ReplyDelete
  3. oh ok...wow...maybe they should have one single base Class EncoderDecoder, that does URI encoding, Normal Escape encoding, Base64, etc....and the respective decodings....and we can just use the methods with the appropriate parameters.....rather than confusing with so many different methods() in the air...and requiring us to write wrapper classes....

    ReplyDelete
  4. Great Post!

    It help us a lot. We are opening the encoded URL in new Window. That Url is related to COGNOS reports. Only problem we faced is, if we use encoded URL and pass it to Window.open function then it creates problem, becauase I have read in on blog that Window.open itself try to encode URL which is passed to it. So, we have set the target proberty of Link and open it in new window.

    Only issue we are still facing is that how to remove address bar of new window and How to use same window when new item is clicked in grid. When we click other item in grid it opens it in fresh window.


    Any ideas then please share.

    Thanks again. Keep posting good articale.

    ReplyDelete
  5. Subodh, Glad if it helped.
    Regarding being able to open popup windows without having address bars showing up, you may want to check out few posts following this link: http://kseesharp.blogspot.com/search?q=modal
    I am sure you will find one of those useful for your purpose. Secondly, having grid items opened in the same window, just make sure you do not have a "target=_blank" or something similar in the hyperlink, since unless you have that specified, links should typically open in the same window when clicked. Let me know if you need anything else...
    Cheers! KC.

    ReplyDelete
  6. Thanks you lot on this solution.
    We got rid of real big headache on
    this esacpe things.
    keep up your good work.

    ReplyDelete
  7. Thanks for posting this - helped us a great deal!

    ReplyDelete
  8. Very nice, thanks for this!

    ReplyDelete
  9. that is very nice post.
    it is very good article specially for me for my website design.

    ReplyDelete
  10. Cool... this really helped me a lot.. Thanks.. :)

    ReplyDelete
  11. There's a better way (more compatible with UTF-8 and also not reliant on a javascript global object):

    (Dependent on System.Web.Extensions.dll)

    using System.Web.Script.Serialization;
    JavaScriptSerializer serialiser = new JavaScriptSerializer();
    serialiser.Serialize("some \"string\"")

    ReplyDelete
  12. Thank you, this help me to sort out a strange bug in my application

    ReplyDelete
  13. Thank you very much,
    It solved my problem.

    Thanks Again

    ReplyDelete
  14. Can you please help me convert
    these 2 javascript functions into C#
    -------------------------------------------------
    //- function Encode
    var strCode=escape("Hello World");
    var resCode="";
    for (i=0; i<strCode.length; i++) {
    resCode += strCode.charCodeAt(i).toString(16);
    }
    //- Display Numeric Value
    document.write(resCode.toUpperCase());
    -------------------------------------------------
    //- function Decode
    var viewCode = "";
    for (i=0; i<resCode.length; i+=2) {
    charCode = parseInt(resCode.substr(i,2), 16);
    viewCode += String.fromCharCode(charCode);
    }
    document.write(unescape(viewCode));
    -------------------------------------------------
    I will really appriciate your help

    TIA

    ReplyDelete
  15. Thanks for you post. It helps me to resolve an issue. But I faced another one - after unescaping of string in javascript I am getting string without new lines? Did you have this problem?

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.