Escaping text in HTML

Thought I just share this little function on its own. I created a simple method that escape (convert) a string to make it ‘safe’ for html display.

public static string EscapeText(string text)
{

string escapeChars2 = @”<>`´àáâãäåèéêëìíîïñòóôõö÷øùúûüýÀÁÂÃÄÅÈÉÊËÌÍÎÏÑÒÓÔÕÖ×ØÙÚÛÜÝ“;

if (string.IsNullOrEmpty(text))

return “”;

else if (text.IndexOfAny(escapeChars2.ToCharArray()) == -1)

return text;

else
{

return text
.Replace(“<“, “&lt;”)
.Replace(“>”, “&gt;”)
.Replace(“&”, “&amp;”)
.Replace(“`”, “&#96;”)
.Replace(“´”, “&acute;”)
.Replace(“à”, “&agrave;”)
.Replace(“á”, “&aacute;”)
.Replace(“â”, “&acirc;”)
.Replace(“ã”, “&atilde;”)
.Replace(“ä”, “&auml;”)
.Replace(“å”, “&aring;”)
.Replace(“è”, “&egrave;”)
.Replace(“é”, “&eacute;”)
.Replace(“ê”, “&ecirc;”)
.Replace(“ë”, “&euml;”)
.Replace(“ì”, “&igrave;”)
.Replace(“í”, “&iacute;”)
.Replace(“î”, “&icirc;”)
.Replace(“ï”, “&iuml;”)
.Replace(“ñ”, “&ntilde;”)
.Replace(“ò”, “&ograve;”)
.Replace(“ó”, “&oacute;”)
.Replace(“ô”, “&ocirc;”)
.Replace(“õ”, “&otilde;”)
.Replace(“ö”, “&ouml;”)
.Replace(“÷”, “&divide;”)
.Replace(“ø”, “&oslash;”)
.Replace(“ù”, “&ugrave;”)
.Replace(“ú”, “&uacute;”)
.Replace(“û”, “&ucirc;”)
.Replace(“ü”, “&uuml;”)
.Replace(“ý”, “&yacute;”)
.Replace(“ÿ”, “&#255;”)
.Replace(“À”, “&Agrave;”)
.Replace(“Á”, “&Aacute;”)
.Replace(“”, “&Acirc;”)
.Replace(“Ô, “&Atilde;”)
.Replace(“Ä”, “&Auml;”)
.Replace(“Å”, “&Aring;”)
.Replace(“È”, “&Egrave;”)
.Replace(“É”, “&Eacute;”)
.Replace(“Ê”, “&Ecirc;”)
.Replace(“Ë”, “&Euml;”)
.Replace(“Ì”, “&Igrave;”)
.Replace(“Í”, “&Iacute;”)
.Replace(“Δ, “&Icirc;”)
.Replace(“Ï”, “&Iuml;”)
.Replace(“Ñ”, “&Ntilde;”)
.Replace(“Ò”, “&Ograve;”)
.Replace(“Ó”, “&Oacute;”)
.Replace(“Ô”, “&Ocirc;”)
.Replace(“Õ”, “&Otilde;”)
.Replace(“Ö”, “&Ouml;”)
.Replace(“×”, “&times;”)
.Replace(“Ø”, “&Oslash;”)
.Replace(“Ù”, “&Ugrave;”)
.Replace(“Ú”, “&Uacute;”)
.Replace(“Û”, “&Ucirc;”)
.Replace(“Ü”, “&Uuml;”)
.Replace(“Ý”, “&Yacute;”);

}

}

There are other ways to do the string matching – like Regular Expressions, but they add some other overhead for a method that does something simple like this.

  1. HTMLWriter 1.3 | Rudolf's mind - pingback on 2011/05/09 at 22:10

Leave a Reply

Trackbacks and Pingbacks:

%d bloggers like this: