Java HTML Encode htmlEncode(String str)

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

Description

html Encode

License

Apache License

Declaration

public static String htmlEncode(String str) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    private static final String invalidStr[] = { ">", "<", "\"", "\\" };
    private static final String escapedStr[] = { "&gt;", "&lt;", "&quot;", "\\\\" };

    public static String htmlEncode(String str) {
        if (str == null) {
            return null;
        }/*from   w w w  .  j ava 2s . co m*/

        for (int i = 0; i < invalidStr.length; i++)
            str = change(str, invalidStr[i], escapedStr[i]);
        return str;
    }

    public static String change(String in, String oldPat, String newPat) {
        if (oldPat.length() == 0)
            return in;
        if (oldPat.length() == 1 && newPat.length() == 1)
            return in.replace(oldPat.charAt(0), newPat.charAt(0));
        if (in.indexOf(oldPat) < 0)
            return in;
        int lastIndex = 0;
        int newIndex = 0;
        StringBuffer newString = new StringBuffer();
        for (;;) {
            newIndex = in.indexOf(oldPat, lastIndex);
            if (newIndex != -1) {
                newString.append(in.substring(lastIndex, newIndex) + newPat);
                lastIndex = newIndex + oldPat.length();
            } else {
                newString.append(in.substring(lastIndex));
                break;
            }
        }
        return newString.toString();
    }
}

Related

  1. HTMLEncode(String s)
  2. htmlEncode(String s, boolean encodeSpecialChars)
  3. htmlEncode(String s, boolean encodeWS)
  4. HtmlEncode(String str)
  5. HTMLEncode(String str)
  6. htmlEncode(String str)
  7. htmlEncode(String str)
  8. htmlEncode(String str)
  9. htmlEncode(String string)