This method is used to insert HTML block dynamically - Java java.lang

Java examples for java.lang:String HTML

Description

This method is used to insert HTML block dynamically

Demo Code


//package com.java2s;

public class Main {
    /**//  www.ja  va  2 s .c o m
     * This method is used to insert HTML block dynamically
     *
     * @param source the HTML code to be processes
     * @param bReplaceNl if true '\n' will be replaced by <br>
     * @param bReplaceTag if true '<' will be replaced by &lt; and 
     *                          '>' will be replaced by &gt;
     * @param bReplaceQuote if true '\"' will be replaced by &quot; 
     */
    public static String formatHtml(String source, boolean bReplaceNl,
            boolean bReplaceTag, boolean bReplaceQuote) {

        StringBuffer sb = new StringBuffer();
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char c = source.charAt(i);
            switch (c) {
            case '\"':
                if (bReplaceQuote)
                    sb.append("&quot;");
                else
                    sb.append(c);
                break;

            case '<':
                if (bReplaceTag)
                    sb.append("&lt;");
                else
                    sb.append(c);
                break;

            case '>':
                if (bReplaceTag)
                    sb.append("&gt;");
                else
                    sb.append(c);
                break;

            case '\n':
                if (bReplaceNl) {
                    if (bReplaceTag)
                        sb.append("&lt;br&gt;");
                    else
                        sb.append("<br>");
                } else {
                    sb.append(c);
                }
                break;

            case '\r':
                break;

            case '&':
                sb.append("&amp;");
                break;

            default:
                sb.append(c);
                break;
            }
        }
        return sb.toString();
    }
}

Related Tutorials