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.
Code
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("&");
case '<' -> out.append("<");
case '>' -> out.append(">");
case '"' -> out.append(""");
case '\'' -> out.append("'");
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
HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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>`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.