HTML-encode the string and convert newlines into <br> tags. Escapes special characters in the string with backslash characters for formatting as a C-like string literal. - CSharp System

CSharp examples for System:String HTML

Description

HTML-encode the string and convert newlines into <br> tags. Escapes special characters in the string with backslash characters for formatting as a C-like string literal.

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System;//from   w ww. j a v  a2 s. c o  m

public class Main{


        /// <summary>
        /// HTML-encode the string and convert newlines into &lt;br/&gt; tags.
        /// </summary>
        /// <returns></returns>
        /// <summary>
        /// Escapes special characters in the string with backslash characters for formatting as a C-like string literal.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string EscapeQuotedString(this string value)
        {
            var sb = new StringBuilder();
            foreach (var ch in value)
            {
                if (ch == '\\') sb.Append("\\\\");
                else if (ch == '/') sb.Append("\\/");
                else if (ch == '\n') sb.Append("\\n");
                else if (ch == '\r') sb.Append("\\r");
                else if (ch == '\t') sb.Append("\\t");
                else if (ch == '\'') sb.Append("\\\'");
                else if (ch == '\"') sb.Append("\\\"");
                else if ((ch < 32) || ch > 127)
                {
                    sb.Append(@"\u");
                    sb.AppendFormat(CultureInfo.InvariantCulture, "{0:x4}", (int)ch);
                }
                else
                {
                    sb.Append(ch);
                }
            }
            return sb.ToString();
        }
}

Related Tutorials