Java HTML Encode htmlSpecialChars(String html)

Here you can find the source of htmlSpecialChars(String html)

Description

html Special Chars

License

Open Source License

Declaration

public static String htmlSpecialChars(String html) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static String htmlSpecialChars(String html) {
        StringBuilder builder = new StringBuilder(html);

        for (int index = 0; index < builder.length(); index++) {
            String toInsert;/*from  w w w. j  a  va  2 s .  c  om*/

            switch (builder.charAt(index)) {
            case '<':
                toInsert = "&lt;";
                break;

            case '>':
                toInsert = "&gt;";
                break;

            case '\'':
                toInsert = "&#39;";
                break;

            case '"':
                toInsert = "&quot;";
                break;

            case '&':
                toInsert = "&amp;";
                break;

            default:
                continue;
            }

            builder.deleteCharAt(index);
            builder.insert(index, toInsert);

            index += toInsert.length() - 1;
        }

        return builder.toString();
    }

    public static String insert(String string, int index, char input) {
        return insert(string, index, input + "");
    }

    public static String insert(String string, int index, String input) {
        if (index <= 0)
            return input + string;

        if (index >= string.length())
            return string + input;

        return string.substring(0, index) + input + string.substring(index);
    }
}

Related

  1. htmlize(CharSequence q)
  2. htmlize(String str)
  3. htmlize(String text)
  4. htmlize(StringBuffer sb)
  5. htmlSpecialChars(String handleStr)
  6. htmlspecialchars(String input)
  7. htmlspecialchars(String s)
  8. htmlspecialchars(String str)
  9. textToHtml(final String s)