Unescape JavaScript’s escape() using C#

Are the any functions in C# that handle escape/unescape like JavaScript?

I have a JSON string like this:

{"Feeds":[{"Url":"www.test.com","FeedType":"Twitter"},{"Url":"www.test2.com","FeedType":"Youtube"}]}

Which looks like this after escape()

%7B%22Feeds%22%3A%5B%7B%22Url%22%3A%22www.test.com%22%2C%22FeedType%22%3A%22Twitter%22%7D%2C%7B%22Url%22%3A%22www.test2.com%22%2C%22FeedType%22%3A%22Youtube%22%7D%5D%7D

In my C# code I would like to unescape this string so that it looks exactly the same as it did before the escape()

Is this possible?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

HttpUtility.UrlDecode should do the trick.

Method 2

escape() is equivalent to

HttpUtility.UrlDecode(str, System.Text.Encoding.Default);

By default the UrlDecode uses UTF8 while escape() don’t.

Method 3

This is the best way I found to work with these:

Encode in C#:

System.Uri.EscapeDataString("<string>");

Decode in JavaScript:

decodeURI("<string>");

Encode in JavaScript:

encodeURI("<string>");

Decode in C#:

System.Uri.UnescapeDataString("<string>");

Update 27-Jan-2016: Just found what seems do be a more compatible way to do it, which also encodes the URI protocol (http://) using javascript:

Encode in JavaScript:

encodeURIComponent("<string>");

Decode in JavaScript:

decodeURIComponent("<string>");

Method 4

Aw man, why do we over-think stuff so much sometimes.
When an API function is being silly, send a karma cuss at the library developer, then work-around it…

HttpUtility.UrlEncode(editext, System.Text.Encoding.Default).Replace("+","%20");

Method 5

    internal static string UnJavascriptEscape(string s)
    {
        // undo the effects of JavaScript's escape function
        return HttpUtility.UrlDecode(s.Replace("+", "%2b"), Encoding.Default);
    }

Method 6

To unescape without having to reference System.Web in order to use HttpUtility, try this:

Str = Str.Replace("+", " ");
Str = Regex.Replace(Str, "%([A-Fa-f\d]{2})", a => "" + Convert.ToChar(Convert.ToInt32(a.Groups[1].Value, 16)));

Also, when I tried HttpUtility.UrlDecode, it didn’t work for special characters áéíóúñ.

Method 7

I spent 8 hours trying to get

HttpUtility.UrlDecode

to work, and gave up and used

HttpUtility.HtmlDecode

which worked instantly.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x