Escape HTML special characters from a StringTag(s): String/Number
public static final String escapeHTML(String s){ StringBuffer sb = new StringBuffer(); int n = s.length(); for (int i = 0; i < n; i++) { char c = s.charAt(i); switch (c) { case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '&': sb.append("&"); break; case '"': sb.append("""); break; case 'à': sb.append("à");break; case 'À': sb.append("À");break; case 'â': sb.append("â");break; case 'Â': sb.append("Â");break; case 'ä': sb.append("ä");break; case 'Ä': sb.append("Ä");break; case 'å': sb.append("å");break; case 'Å': sb.append("Å");break; case 'æ': sb.append("æ");break; case 'Æ': sb.append("Æ");break; case 'ç': sb.append("ç");break; case 'Ç': sb.append("Ç");break; case 'é': sb.append("é");break; case 'É': sb.append("É");break; case 'è': sb.append("è");break; case 'È': sb.append("È");break; case 'ê': sb.append("ê");break; case 'Ê': sb.append("Ê");break; case 'ë': sb.append("ë");break; case 'Ë': sb.append("Ë");break; case 'ï': sb.append("ï");break; case 'Ï': sb.append("Ï");break; case 'ô': sb.append("ô");break; case 'Ô': sb.append("Ô");break; case 'ö': sb.append("ö");break; case 'Ö': sb.append("Ö");break; case 'ø': sb.append("ø");break; case 'Ø': sb.append("Ø");break; case 'ß': sb.append("ß");break; case 'ù': sb.append("ù");break; case 'Ù': sb.append("Ù");break; case 'û': sb.append("û");break; case 'Û': sb.append("Û");break; case 'ü': sb.append("ü");break; case 'Ü': sb.append("Ü");break; case '®': sb.append("®");break; case '©': sb.append("©");break; case '€': sb.append("€"); break; // be carefull with this one (non-breaking whitee space) case ' ': sb.append(" ");break; default: sb.append(c); break; } } return sb.toString(); }
Submitted by S. Bayer. (PS. Thanks to ablage_p for the fix!)
public static String stringToHTMLString(String string) { StringBuffer sb = new StringBuffer(string.length()); // true if last char was blank boolean lastWasBlankChar = false; int len = string.length(); char c; for (int i = 0; i < len; i++) { c = string.charAt(i); if (c == ' ') { // blank gets extra work, // this solves the problem you get if you replace all // blanks with , if you do that you loss // word breaking if (lastWasBlankChar) { lastWasBlankChar = false; sb.append(" "); } else { lastWasBlankChar = true; sb.append(' '); } } else { lastWasBlankChar = false; // // HTML Special Chars if (c == '"') sb.append("""); else if (c == '&') sb.append("&"); else if (c == '<') sb.append("<"); else if (c == '>') sb.append(">"); else if (c == '\n') // Handle Newline sb.append("<br/>"); else { int ci = 0xffff & c; if (ci < 160 ) // nothing special only 7 Bit sb.append(c); else { // Not 7 Bit use the unicode system sb.append("&#"); sb.append(new Integer(ci).toString()); sb.append(';'); } } } } return sb.toString(); }