如何解码用JavaScriptStringEncoded编码的字符串?

Sam*_* S. 6 javascript c# encoding json

有没有一种方法来解码在C#中用HttpUtility.JavaScriptStringEncode()编码的字符串?

示例编码字符串:

<div class=\"header\"><h2>\u00FC<\/h2><script>\n<\/script>\n
Run Code Online (Sandbox Code Playgroud)

我的临时解决方案是:

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;
}
Run Code Online (Sandbox Code Playgroud)

ben*_*and 0

不,您必须自己实施。原因是这种方法没有有意的用途!对于您可能想要实现的目标,为什么不直接使用

HttpServerUtility.HtmlEncode(...)
Run Code Online (Sandbox Code Playgroud)

HttpServerUtility.HtmlDecode(...)
Run Code Online (Sandbox Code Playgroud)