Escape String for Html - Java java.lang

Java examples for java.lang:String HTML

Description

Escape String for Html

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String strString = "java2s.com";
        System.out.println(checkHtmlView(strString));
    }/*from   w ww.j a v a2  s  . com*/

    public static String checkHtmlView(String strString) {
        String strNew = "";

        try {
            StringBuffer strTxt = new StringBuffer("");

            char chrBuff;
            int len = strString.length();

            for (int i = 0; i < len; i++) {
                chrBuff = (char) strString.charAt(i);

                switch (chrBuff) {
                case '<':
                    strTxt.append("&lt;");
                    break;
                case '>':
                    strTxt.append("&gt;");
                    break;
                case '"':
                    strTxt.append("&quot;");
                    break;
                case 10:
                    strTxt.append("<br>");
                    break;
                case ' ':
                    strTxt.append("&nbsp;");
                    break;
                //case '&' :
                //strTxt.append("&amp;");
                //break;
                default:
                    strTxt.append(chrBuff);
                }
            }

            strNew = strTxt.toString();

        } catch (Exception ex) {
            return null;
        }

        return strNew;
    }
}

Related Tutorials