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

如何将字符串中的HTML实体替换为对应字符?

解码HTML实体为对应字符的方法

我有一个包含多种HTML实体的字符串,示例如下:

var price = "CHF 150.– (brutto)";

需要将诸如–这类HTML实体替换为对应的字符,得到结果:

"CHF 150.- (brutto)";

浏览器端解决方案

利用浏览器DOM的解析能力是最简便的方式,代码如下:

function decodeHtmlEntities(str) {
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = str;
  return tempDiv.textContent || tempDiv.innerText;
}

// 调用示例
const price = "CHF 150.– (brutto)";
const decodedPrice = decodeHtmlEntities(price);
console.log(decodedPrice); // 输出 "CHF 150.- (brutto)"

Node.js环境解决方案

Node.js没有内置DOM环境,可使用第三方库he处理:

  1. 安装依赖:
npm install he
  1. 解码代码:
const he = require('he');

const price = "CHF 150.– (brutto)";
const decodedPrice = he.decode(price);
console.log(decodedPrice); // 输出目标字符串

自定义少量实体替换(仅适用于已知实体)

如果只需要处理特定几个HTML实体,可直接用正则替换:

function decodeSpecificEntities(str) {
  return str
    .replace(/–/g, '-')
    .replace(/"/g, '"')
    // 按需添加更多实体映射规则
}

const price = "CHF 150.– (brutto)";
console.log(decodeSpecificEntities(price)); // 输出结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:15:06