patternjavaCritical
Remove HTML tags from a String
Viewed 0 times
tagsfromremovehtmlstring
Problem
Is there a good way to remove HTML from a Java string? A simple regex like
will work, but some things like
replaceAll("\\", "")
will work, but some things like
& won't be converted correctly and non-HTML between the two angle brackets will be removed (i.e. the .*? in the regex will disappear).Solution
Use a HTML parser instead of regex. This is dead simple with Jsoup.
Jsoup also supports removing HTML tags against a customizable whitelist, which is very useful if you want to allow only e.g. `
See also:
public static String html2text(String html) {
return Jsoup.parse(html).text();
}Jsoup also supports removing HTML tags against a customizable whitelist, which is very useful if you want to allow only e.g. `
, and `.See also:
- RegEx match open tags except XHTML self-contained tags
- What are the pros and cons of the leading Java HTML parsers?
- XSS prevention in JSP/Servlet web application
Code Snippets
public static String html2text(String html) {
return Jsoup.parse(html).text();
}Context
Stack Overflow Q#240546, score: 657
Revisions (0)
No revisions yet.