Java HTML Encode toHTMLString(String str)

Here you can find the source of toHTMLString(String str)

Description

Converts the given unicode string to an html string where special characters are converted to &#xxx; sequences (xxx is the unicode value of the character)

License

Open Source License

Declaration

final public static String toHTMLString(String str) 

Method Source Code

//package com.java2s;
/* //from  w ww  . j a  v  a 2  s.  c  om
 GeoGebra - Dynamic Mathematics for Everyone
 http://www.geogebra.org
    
 This file is part of GeoGebra.
    
 This program is free software; you can redistribute it and/or modify it 
 under the terms of the GNU General Public License as published by 
 the Free Software Foundation.
     
 */

public class Main {
    /**
     * Converts the given unicode string 
     * to an html string where special characters are
     * converted to <code>&#xxx;</code> sequences (xxx is the unicode value
     * of the character)
     * 
     * @author Markus Hohenwarter
     */
    final public static String toHTMLString(String str) {
        if (str == null)
            return null;

        StringBuffer sb = new StringBuffer();

        // convert every single character and append it to sb
        int len = str.length();
        for (int i = 0; i < len; i++) {
            char c = str.charAt(i);
            int code = c;

            //  standard characters have code 32 to 126
            if ((code >= 32 && code <= 126)) {
                switch (code) {
                case 60:
                    sb.append("&lt;");
                    break; //   <
                case 62:
                    sb.append("&gt;");
                    break; // >

                default:
                    //do not convert                
                    sb.append(c);
                }
            }
            // special characters
            else {
                switch (code) {
                case 10:
                case 13: // replace LF or CR with <br/>
                    sb.append("<br/>\n");
                    break;

                case 9: // replace TAB with space
                    sb.append("&nbsp;"); // space
                    break;

                default:
                    //  convert special character to escaped HTML               
                    sb.append("&#");
                    sb.append(code);
                    sb.append(';');
                }
            }
        }
        return sb.toString();
    }
}

Related

  1. toHtmlLine(String input)
  2. toHTMLString(String in)
  3. toHtmlString(String input)
  4. toHTMLString(String org)
  5. toHtmlString(String s)
  6. toHtmlText(String s)
  7. toHtmlText(String text)
  8. toHtmlTitle(final String title)
  9. toHtmlUrl(String url, String displayLabel)