You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript移除字符串中的HTML标签及其内容?

移除字符串中HTML标签及其内容的JavaScript方法

你可以通过调整正则表达式,直接匹配并移除整个HTML标签块(包括开始标签、内部内容和结束标签),实现预期效果。

解决方案代码

const test = "This is outside the HTML tag. <title>How to remove an HTML element using JavaScript ?</title>";
const cleanedStr = test.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/gi, '').trim();
console.log(cleanedStr); // 输出: "This is outside the HTML tag."

正则说明

  • <[^>]+>:匹配HTML开始标签(比如<title>),[^>]+确保匹配到标签的闭合>为止
  • [\s\S]*?:非贪婪匹配标签内部的所有内容,[\s\S]覆盖所有字符(包括换行),*?避免过度匹配到后面的其他标签
  • <\/[^>]+>:匹配对应的HTML结束标签(比如</title>)

处理自闭合标签(可选)

如果字符串中存在自闭合标签(如<br/>、<img src="xxx"/>),可以扩展正则同时匹配这类标签:

const cleanedStr = test.replace(/<[^>]+>[\s\S]*?<\/[^>]+>|<[^>]+\/>/gi, '').trim();

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:20:21