Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode a string encoded with JavaScriptStringEncoded?

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;
}
like image 210
Samet S. Avatar asked Mar 19 '26 00:03

Samet S.


1 Answers

System.Text.Json.JsonSerializer.Deserialize(string json) will do it for you except the case when original string was null - it returns "" instead.Do not forget to put encoded string inside double quotes before. HttpUtility.JavaScriptStringEncode(str,true) overload will do it automatically.

like image 127
Iona L Avatar answered Mar 20 '26 12:03

Iona L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!