12

Is there a method to decode a string encoded with HttpUtility.JavaScriptStringEncode() in C#?

Example encoded string:

<div class=\"header\"><h2>\u00FC<\/h2><script>\n<\/script>\n

My temporary solution is:

public static string JavaScriptStringDecode(string source)
{
    // Replace some chars.
    var decoded = source.Replace(@"\'", "'")
                .Replace(@"\""", @"""")
                .Replace(@"\/", "/")
                .Replace(@"\t", "\t")
                .Replace(@"\n", "\n");

    // Replace unicode escaped text.
    var rx = new Regex(@"\\[uU]([0-9A-F]{4})");

    decoded = rx.Replace(decoded, match => ((char)Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber))
                                            .ToString(CultureInfo.InvariantCulture));

    return decoded;
}
Samet S.
  • 475
  • 1
  • 10
  • 21

3 Answers3

1

You could use

HttpUtility.UrlDecode

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

also answered here: Unescape JavaScript's escape() using C#

But, UrlDecode has some significant limitations around certain characters (like + signs, which javascript doesn't unescape) and any character values >= 128. Using Microsoft.JScript.GlobalObject.unescape is probably the most reliable, but I don't know how well it performs (i.e. what the backing language is. I'd imagine it's fast given it's a lib at this point).

Community
  • 1
  • 1
0

No, you would have to implement that yourself. The reason is that there is just no intented usage for such a method! For what you are probably trying to achieve, why not just use

HttpServerUtility.HtmlEncode(...)

and

HttpServerUtility.HtmlDecode(...)
0

I use HttpUtility.UrlEncode instead of HttpUtility.JavaScriptStringEncode, and then HttpUtility.UrlDecode.

Oranit Dar
  • 1,539
  • 18
  • 17