Unescape JavaScript's escape() using C#

后端 未结 7 1728
不思量自难忘°
不思量自难忘° 2020-12-08 06:29

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

I have a JSON string like this:

{\"Feeds\":[{\"Url\":\"www.test.com\",\"FeedTy

相关标签:
7条回答
  • 2020-12-08 06:50

    HttpUtility.UrlDecode should do the trick.

    0 讨论(0)
  • 2020-12-08 06:58

    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 áéíóúñ.

    0 讨论(0)
  • 2020-12-08 06:59
        internal static string UnJavascriptEscape(string s)
        {
            // undo the effects of JavaScript's escape function
            return HttpUtility.UrlDecode(s.Replace("+", "%2b"), Encoding.Default);
        }
    
    0 讨论(0)
  • 2020-12-08 07:04

    escape() is equivalent to

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

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

    0 讨论(0)
  • 2020-12-08 07:04

    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>");
    
    0 讨论(0)
  • 2020-12-08 07:10

    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");
    
    0 讨论(0)
提交回复
热议问题