Java HTML Encode htmlEncode(String s, boolean encodeWS)

Here you can find the source of htmlEncode(String s, boolean encodeWS)

Description

html Encode

License

Open Source License

Declaration

public static String htmlEncode(String s, boolean encodeWS) 

Method Source Code

//package com.java2s;

public class Main {
    public static String htmlEncode(String s, boolean encodeWS) {
        if (s == null)
            return null;
        char[] ca = s.toCharArray();
        StringBuffer res = new StringBuffer(ca.length);
        int ls = 0;
        boolean blankMet = true;
        for (int i = 0; i < ca.length; i++) {
            switch (ca[i]) {
            case '<':
                res.append(ca, ls, i - ls);
                res.append("&lt;");
                ls = i + 1;/*from  w ww.  java 2s  . c  o m*/
                break;
            case '>':
                res.append(ca, ls, i - ls);
                res.append("&gt;");
                ls = i + 1;
                break;
            case '"':
                res.append(ca, ls, i - ls);
                res.append("&quot;");
                ls = i + 1;
                break;
            case '&':
                res.append(ca, ls, i - ls);
                res.append("&amp;");
                ls = i + 1;
                break;
            case ' ':
                if (blankMet && encodeWS) {
                    res.append(ca, ls, i - ls);
                    res.append("&nbsp;");
                    ls = i + 1;
                } else
                    blankMet = true;
                break;
            case '\n':
                if (encodeWS) {
                    res.append(ca, ls, i - ls);
                    res.append("<BR>");
                    ls = i + 1;
                }
                break;
            case '\r':
                if (encodeWS) {
                    res.append(ca, ls, i - ls);
                    ls = i + 1;
                }
                break;
            default:
                if (ca[i] > 127) { // no unicode
                    res.append(ca, ls, i - ls);
                    res.append("&#;" + (int) ca[i]);
                    ls = i + 1;
                }
                blankMet = false;
            }
        }
        if (ls < ca.length)
            res.append(ca, ls, ca.length - ls);
        return res.toString();
    }
}

Related

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