Escape Quote in C# for javascript consumption

后端 未结 9 1248
天涯浪人
天涯浪人 2020-11-27 17:24

I have a ASP.Net web handler that returns results of a query in JSON format

public static String dt2JSON(DataTable dt)
{
    String s = \"{\\\"rows\\\":[\";
         


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 17:54

    Here is a rework of @Bryan Legend's answer with Linq:

    public static string EncodeJavaScriptString(string s)
        => string.Concat(s.Select(c => {
            switch (c)
            {
                case '\"': return "\\\"";
                case '\\': return "\\\\";
                case '\b': return "\\b";
                case '\f': return "\\f";
                case '\n': return "\\n";
                case '\r': return "\\r";
                case '\t': return "\\t";
                default: return (c < 32 || c > 127) && !char.IsLetterOrDigit(c) ? $"\\u{(int)c:X04}" : c.ToString();
            }}));
    

    Try it Online!

    changelog:

    • Remove double quoting wrapping since I do it in the js
    • Use expression body
    • Use a cleaner switch
    • Use Linq
    • Add a check for Letter to allow é

提交回复
热议问题