Java HTML Encode htmlEncode(String string)

Here you can find the source of htmlEncode(String string)

Description

html Encode

License

BSD License

Parameter

Parameter Description
string String

Return

String

Declaration

public static String htmlEncode(String string) 

Method Source Code

//package com.java2s;
/**// w  w  w  .j a v a 2  s .com
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */

public class Main {
    /**
     *
     * @param string
     *            String
     * @return String
     */
    public static String htmlEncode(String string) {
        String encoded = replaceString(string, '&', "&");
        encoded = replaceString(encoded, '<', "&lt;");
        return replaceString(encoded, '>', "&gt;");
    }

    /**
     *
     * @param original
     *            String
     * @param oldChar
     *            char
     * @param newString
     *            String
     * @return String
     */
    public static String replaceString(final String original, char oldChar, final String newString) {
        int index = original.indexOf(oldChar);
        if (index < 0) {
            return original;
        } else {
            final String replace = newString == null ? "" : newString;
            final StringBuilder buf = new StringBuilder(Math.max(16, original.length() + replace.length()));
            int last = 0;
            while (index != -1) {
                buf.append(original.substring(last, index));
                buf.append(replace);
                last = index + 1;
                index = original.indexOf(oldChar, last);
            }
            buf.append(original.substring(last));
            return buf.toString();
        }
    }

    /**
     *
     * @param original
     *            String
     * @param oldString
     *            String
     * @param newString
     *            String
     * @return String
     */
    public static String replaceString(final String original, final String oldString, final String newString) {
        int index = original.indexOf(oldString);
        if (index < 0) {
            return original;
        } else {
            final String replace = newString == null ? "" : newString;
            final StringBuilder buf = new StringBuilder(Math.max(16, original.length() + replace.length()));
            int last = 0;
            while (index != -1) {
                buf.append(original.substring(last, index));
                buf.append(replace);
                last = index + oldString.length();
                index = original.indexOf(oldString, last);
            }
            buf.append(original.substring(last));
            return buf.toString();
        }
    }
}

Related

  1. htmlEncode(String str)
  2. htmlEncode(String str)
  3. htmlEncode(String str)
  4. htmlEncode(String string)
  5. HTMLEncode(String string)
  6. HtmlEncode(String strInput)
  7. htmlEncode(String strSrc)
  8. htmlEncode(String strSrc)
  9. htmlEncode(String text)