Escape HTML Entities In Text

Escape the five HTML entities a text node needs (&, <, >, quotes) with a tiny switch, so user-provided strings can be embedded in markup safely.

JavaSecurity Boundaries

Code

snippet
public class HtmlEscape {

    // Escape the five HTML entities a text node requires: & < > " '
    static String escape(String text) {
        StringBuilder out = new StringBuilder(text.length() + 16);
        for (int i = 0; i < text.length(); i++) {
            switch (text.charAt(i)) {
                case '&'  -> out.append("&amp;");
                case '<'  -> out.append("&lt;");
                case '>'  -> out.append("&gt;");
                case '"'  -> out.append("&quot;");
                case '\'' -> out.append("&#39;");
                default   -> out.append(text.charAt(i));
            }
        }
        return out.toString();
    }

    public static void main(String[] args) {
        String comment = "Q&A: <b>bold</b> & \"quotes\" 'apostrophe'";
        // 转义后再拼进标记,用户输入永远只是文本,不构成注入面
        System.out.println("<p>" + escape(comment) + "</p>");
    }
}

How it works

Escape HTML Entities In Text reduces to the class HtmlEscape and the functions escape and main.

Iteration happens inside for (int i = 0; i < text.length(); i++) — everything outside it runs once.

Using it

The primary signature is static String escape(String text)

The demo output is labeled (<p>), so every printed line maps back to its originating operation.

The sequence escape lives in main; running the file triggers it.

Key statements

return out.toString();

Interactive Tools for This Topic

FAQ

What does Escape HTML Entities In Text print when run?
Run it as a complete program — the output lines carry labels such as `<p>`.