最近一个需求需要过滤掉前端传过来的字符串中的HTML标签,查了很多,最后觉得这种办法最简单,记录一下解决方法,方便以后查阅。

Jsoup 是一个流行的HTML解析库,添加依赖即可。

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.14.3</version>
</dependency>

伪代码:

String content = "测试内容<div>测试内容</div><div>测试内容</div><div>测试内容</div><div>测试内容</div><div>测试内容</div><div>测试内容</div><div>测试内容<p><br></p></div>";
String newContent = Jsoup.parse(content).text();
System.out.println(newContent);

打印结果:

测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容 测试内容

需求实现。