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

NodeJS:移除文本HTML标签并保留图片alt属性内容

提取HTML文本并保留表情符号(从img的alt属性)

问题场景

有一段转义后的HTML字符串,其中表情以<img>标签形式存在,表情符号存储在alt属性中。示例代码如下:

const htmlText = '&lt;p&gt;test emoji &lt;span title=&quot;Smile&quot; class=&quot;animated-emoticon-20-smile&quot;&gt;&lt;img title=&quot;Smile&quot; alt=&quot;🙂&quot;&gt;&lt;/span&gt; and more &lt;span title=&quot;Emo&quot; class=&quot;animated-emoticon-20-emo&quot;&gt;&lt;img title=&quot;Emo&quot; alt=&quot;😑&quot;&gt;&lt;/span&gt;&lt;span title=&quot;Star eyes&quot; class=&quot;animated-emoticon-20-stareyes&quot;&gt;&lt;img title=&quot;Star eyes&quot; alt=&quot;🤩&quot;&gt;&lt;/span&gt;&lt;/p&gt;'

需要将其转换为不含任何HTML标签,但保留表情符号的纯文本,期望输出:

test emoji 🙂 and more 😑🤩

此前使用正则htmlText.replace(/&lt;[^&gt;]+&gt;/g, '')会直接删除所有标签(包括表情相关的),仅得到'test emoji and more ',无法保留表情。


解决方案

方案一:调整正则表达式(适合简单场景)

因为原字符串是转义后的HTML(<>已转义为&lt;/&gt;,双引号转义为&quot;),所以需要先匹配转义后的<img>标签,提取alt属性值替换标签,再移除剩余的HTML标签:

const htmlText = '&lt;p&gt;test emoji &lt;span title=&quot;Smile&quot; class=&quot;animated-emoticon-20-smile&quot;&gt;&lt;img title=&quot;Smile&quot; alt=&quot;🙂&quot;&gt;&lt;/span&gt; and more &lt;span title=&quot;Emo&quot; class=&quot;animated-emoticon-20-emo&quot;&gt;&lt;img title=&quot;Emo&quot; alt=&quot;😑&quot;&gt;&lt;/span&gt;&lt;span title=&quot;Star eyes&quot; class=&quot;animated-emoticon-20-stareyes&quot;&gt;&lt;img title=&quot;Star eyes&quot; alt=&quot;🤩&quot;&gt;&lt;/span&gt;&lt;/p&gt;'

// 第一步:提取img的alt值,替换整个img标签
const withEmojis = htmlText.replace(/&lt;img[^&gt;]+alt=&quot;([^&quot;]+)&quot;[^&gt;]*&gt;/g, '$1');
// 第二步:移除所有剩余的转义HTML标签
const result = withEmojis.replace(/&lt;[^&gt;]+&gt;/g, '');

console.log(result); // 输出:test emoji 🙂 and more 😑🤩

注意:该正则假设alt属性用双引号包裹且转义为&quot;,如果HTML格式有变化(比如单引号、无引号),需要调整正则。

方案二:DOM解析(更健壮)

用浏览器原生DOM解析处理HTML,能自动处理各种标签格式,避免正则的局限性:

const htmlText = '&lt;p&gt;test emoji &lt;span title=&quot;Smile&quot; class=&quot;animated-emoticon-20-smile&quot;&gt;&lt;img title=&quot;Smile&quot; alt=&quot;🙂&quot;&gt;&lt;/span&gt; and more &lt;span title=&quot;Emo&quot; class=&quot;animated-emoticon-20-emo&quot;&gt;&lt;img title=&quot;Emo&quot; alt=&quot;😑&quot;&gt;&lt;/span&gt;&lt;span title=&quot;Star eyes&quot; class=&quot;animated-emoticon-20-stareyes&quot;&gt;&lt;img title=&quot;Star eyes&quot; alt=&quot;🤩&quot;&gt;&lt;/span&gt;&lt;/p&gt;'

// 创建临时DOM容器
const tempDiv = document.createElement('div');
// 插入转义后的HTML,浏览器会自动解析为真实DOM
tempDiv.innerHTML = htmlText;

// 遍历所有img标签,替换为其alt文本
tempDiv.querySelectorAll('img').forEach(img => {
  img.replaceWith(img.alt);
});

// 提取纯文本
const result = tempDiv.textContent.trim();

console.log(result); // 输出:test emoji 🙂 and more 😑🤩

优势:能处理任意格式的HTML(比如属性顺序、换行、额外空格等),无需担心正则匹配不到的情况。如果在Node.js环境使用,可借助jsdom库模拟DOM。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:54:33