Java String escape special characters & < > " for HTML document

Description

Java String escape special characters & < > " for HTML document


//package com.demo2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s = "demo2s.com &<>\"\"";
        System.out.println(htmlEscape(s));
    }/*from www .  jav a 2s.  c om*/

    /**
     * Escapes special characters (& < > ") from a string so it can safely be
     * included in an HTML document. (same as <code>xmlEscape</code> except that
     * <code>htmlEscape</code> does not escape the apostrophe character).
     */
    public static String htmlEscape(String s) {
        StringBuilder sb = null;
        String replacement;
        int start = 0; // the earliest input position we haven't copied yet.
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
            case '"':
                replacement = "&quot;";
                break;
            case '&':
                replacement = "&amp;";
                break;
            case '<':
                replacement = "&lt;";
                break;
            case '>':
                replacement = "&gt;";
                break;
            default:
                replacement = null;
            }

            if (replacement != null) {
                if (sb == null) {
                    sb = new StringBuilder(s.length() + replacement.length() - 1);
                }
                if (i > start) {
                    // we have to copy some of the earlier string.
                    sb.append(s.substring(start, i));
                }
                sb.append(replacement);
                start = i + 1;
            }
        }
        // now possibly also copy what's leftover in the input string.
        if (start > 0) {
            sb.append(s.substring(start));
        }

        if (sb != null) {
            return sb.toString();
        }
        return s;
    }
}



PreviousNext

Related