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

在JavaScript中如何使用sanitize-html将<br />标签替换为空格

使用sanitize-html实现<br/>标签替换为空格的方法

操作步骤

  • 第一步:安装sanitize-html依赖
npm install sanitize-html
  • 第二步:编写转换逻辑,通过transformTags配置将<br/>标签替换为单个空格,同时保留需要的<p>标签,示例代码如下:
const sanitizeHtml = require('sanitize-html');

const inputHtml = '<p>Hello world!<br/>I am here</p>';
const outputHtml = sanitizeHtml(inputHtml, {
  // 配置允许保留的标签,可根据自身需求扩展
  allowedTags: ['p'],
  // 自定义标签转换规则
  transformTags: {
    'br': () => {
      // 将br标签直接替换为单个空格
      return { text: ' ' };
    }
  }
});

console.log(outputHtml); // 输出结果:<p>Hello world! I am here</p>

补充说明

如果存在多个连续<br/>标签的场景,转换后可能出现多个连续空格,可通过额外的正则替换合并空白:

const finalHtml = outputHtml.replace(/\s+/g, ' ');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:18:02