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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With