本文介绍使用 javascript 将常见 html 实体(如 `–`、`&` 等)转换为原始字符的实用方法,提供可扩展的映射函数,并说明其局限性与更健壮的替代方案。
在 Web 开发中,我们常会遇到包含 HTML 实体的字符串(例如从 API 返回或服务端渲染的文本),如:
var price = "CHF 150.– (brutto)";
目标是将其转换为可读的纯文本:”CHF 150.- (brutto)”。最直接的方式是建立一个实体到字符的映射表,并用正则匹配替换。
以下是一个轻量、可控且易于维护的实现:
function replaceHTMLEntities(str) {
const htmlEntities = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'",
'–': '-',
'—': '—',
' ': ' ',
'©': '©',
'®': '®',
};
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"
✅ 优点: