Java HTML Filter filterHtmlAndTruncate(String s)

Here you can find the source of filterHtmlAndTruncate(String s)

Description

filter Html And Truncate

License

Apache License

Declaration

public static String filterHtmlAndTruncate(String s) 

Method Source Code

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

public class Main {
    public static final int MAX_CONTENT_LENGTH = 255;
    public static final int MAX_WORD_LENGTH = 20;

    public static String filterHtmlAndTruncate(String s) {
        return filterHtmlAndTruncate(s, MAX_CONTENT_LENGTH);
    }/*from w w  w.  jav  a 2 s. c o m*/

    public static String filterHtmlAndTruncate(String s, int maxLength) {
        String content = filterHtml(s);

        // then truncate, if necessary
        if (content == null) {
            return "";
        } else {
            StringBuilder buf = new StringBuilder();

            String words[] = content.split("\\s");
            for (int i = 0; i < words.length; i++) {
                if (buf.length() + words[i].length() > maxLength) {
                    buf.append("...");
                    return buf.toString();
                } else if (words[i].length() > MAX_WORD_LENGTH) {
                    buf.append(words[i].substring(0, MAX_WORD_LENGTH));
                    buf.append("...");
                    return buf.toString();
                } else {
                    buf.append(words[i]);
                    if ((i + 1) < words.length) {
                        buf.append(" ");
                    }
                }
            }

            return buf.toString();
        }
    }

    /**
     * Filters out all HTML tags.
     *
     * @param s   the String to filter
     * @return    the filtered String
     */
    public static String filterHtml(String s) {
        if (s == null) {
            return null;
        }

        s = s.replaceAll("&lt;", "");
        s = s.replaceAll("&gt;", "");
        s = s.replaceAll("&nbsp;", "");
        s = s.replaceAll("(?s)<!--.*?-->", "");
        return s.replaceAll("(?s)<.*?>", "");
    }
}

Related

  1. filterHTML(String input)
  2. filterHTML(String input)
  3. filterHtml(String input)
  4. filterHTML(String s)
  5. filterHtml(String s)
  6. filterHtmlAndTruncate(String s)
  7. filterHtmlTag(String body)
  8. filterHtmlTag(String content)
  9. filterHtmlTag(String input)