C# ASP.NET 中html常见转义字符的处理

C# ASP.NET 中html常见转义字符的处理
using System;

namespace ConsoleApp31
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(HtmlToEsc("有    空    格"));
            Console.WriteLine(EscToHtml("有   空     格"));
            Console.Read();
        }

        /// <summary>
        /// Html to Esc
        /// </summary>
        /// <param name="input">input</param>
        /// <returns></returns>
        public static string HtmlToEsc(string input)
        {
            if (string.IsNullOrEmpty(input)) { return ""; }

            input = input.Replace("&", "&amp;")
                        .Replace("'", "&#39;")
                        .Replace("\"", "&quot;")
                        .Replace("<", "&lt;")
                        .Replace(">", "&gt;")
                        .Replace(" ", "&nbsp;")
                        .Replace("©", "&copy;")
                        .Replace("®", "&reg;")
                        .Replace("™", "&#8482;");
            return input;
        }

        /// <summary>
        /// Esc to Html
        /// </summary>
        /// <param name="input">input</param>
        /// <returns></returns>
        public static string EscToHtml(string input)
        {
            if (string.IsNullOrEmpty(input)) { return ""; }

            input = input.Replace("&#8482;", "™")
                        .Replace("&reg;", "®")
                        .Replace("&copy;", "©")
                        .Replace("&nbsp;", " ")
                        .Replace("&gt;", ">")
                        .Replace("&lt;", "<")
                        .Replace("&quot;", "\"")
                        .Replace("&#39;", "'")
                        .Replace("&amp;", "&");
            return input;
        }
    }
}

作者最新文章
C# 使用 CSVHelper 操作 csv 文件, .net core, .net framework 读取写入 csv 文件
C# 实现字符串文本换行的方法,文本如何换行
C# 如何循环读取文件每一行文本内容
C# DateTime AddMonths 的错误用法导致跳过日期
C# 全角转换半角,半角转换为全角