
本文介绍使用 javascript 将常见 html 实体(如 `–`、`&` 等)转换为原始字符的实用方法,提供可扩展的映射函数,并说明其局限性与更健壮的替代方案。
在 Web 开发中,我们常会遇到包含 html 实体的字符串(例如从 API 返回或服务端渲染的文本),如:
var price = "CHF 150.– (brutto)";
目标是将其转换为可读的纯文本:”CHF 150.- (brutto)”。最直接的方式是建立一个实体到字符的映射表,并用正则匹配替换。
以下是一个轻量、可控且易于维护的实现:
function replaceHTMLEntities(str) { const htmlEntities = { '&': '&', 'zuojiankuohaophpcn': '<', 'youjiankuohaophpcn': '>', '"': '"', ''': "'", '–': '-', '—': '—', ' ': ' ', '©': '©', '®': '®', }; return str.replace(/&[w#]+;/g, entity => { return htmlEntities[entity] || entity; }); } // 使用示例 console.log(replaceHTMLEntities("CHF 150.– (brutto)")); // → "CHF 150.- (brutto)" console.log(replaceHTMLEntities("He said "Hello" and © 2024")); // → "He said "Hello" and © 2024"
✅ 优点:
立即学习“前端免费学习笔记(深入)”;
⚠️ 注意事项:
function decodeHTMLEntities(str) { const el = document.createElement('div'); el.innerHTML = str; return el.textContent || el.innerText || ''; } // ✅ 支持 –, –, – 等全部标准实体 console.log(decodeHTMLEntities("CHF 150.– or – or –")); // → "CHF 150.— or — or —"
? 小结:对于已知有限实体的简单场景,自定义映射函数高效清晰;若需全面、标准兼容的解码能力,优先采用 document.createElement 的原生方式——它由浏览器严格遵循 HTML 规范实现,兼顾安全性与完整性。