在JavaScript中,将包含HTML实体字符的字符串转换为普通字符

在JavaScript中,将包含HTML实体字符的字符串转换为普通字符有几种方法:

1. 使用 DOMParser(推荐)

javascript 复制代码
function decodeHTMLEntities(text) {
    const textArea = document.createElement('textarea');
    textArea.innerHTML = text;
    return textArea.value;
}

// 或者使用 DOMParser
function decodeHTMLEntities(text) {
    const doc = new DOMParser().parseFromString(text, 'text/html');
    return doc.documentElement.textContent;
}

// 示例
const encodedString = "Hello & Welcome <world>";
const decodedString = decodeHTMLEntities(encodedString);
console.log(decodedString); // "Hello & Welcome <world>"

2. 使用 textarea 元素

javascript 复制代码
function decodeHTMLEntities(text) {
    const textarea = document.createElement('textarea');
    textarea.innerHTML = text;
    return textarea.value;
}

// 示例
const result = decodeHTMLEntities("John &amp; Jane &copy; 2023");
console.log(result); // "John & Jane © 2023"

3. 使用正则表达式替换(适用于常见实体)

javascript 复制代码
function decodeHTMLEntities(text) {
    const entities = {
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&quot;': '"',
        '&#39;': "'",
        '&nbsp;': ' ',
        '&copy;': '©',
        '&reg;': '®'
    };
    
    return text.replace(/&[a-z]+;/g, match => {
        return entities[match] || match;
    });
}

// 示例
const result = decodeHTMLEntities("Price &lt; $100 &amp; free shipping");
console.log(result); // "Price < $100 & free shipping"

4. 处理数字实体

javascript 复制代码
function decodeHTMLEntities(text) {
    return text.replace(/&#(\d+);/g, (match, dec) => {
        return String.fromCharCode(dec);
    }).replace(/&#x([0-9a-f]+);/gi, (match, hex) => {
        return String.fromCharCode(parseInt(hex, 16));
    });
}

// 示例
const result = decodeHTMLEntities("A&#65; B&#x42;");
console.log(result); // "AA BB"

5. 完整的解决方案

javascript 复制代码
function decodeHTMLEntities(text) {
    // 创建临时元素
    const textArea = document.createElement('textarea');
    textArea.innerHTML = text;
    
    // 处理数字实体(如果需要)
    let decoded = textArea.value;
    decoded = decoded.replace(/&#(\d+);/g, (match, dec) => {
        return String.fromCharCode(dec);
    });
    
    return decoded;
}

// 或者使用更简单的方法
function decodeHTMLEntities(text) {
    const element = document.createElement('div');
    element.innerHTML = text;
    return element.textContent || element.innerText || '';
}

使用示例

javascript 复制代码
// 测试各种HTML实体
const testCases = [
    "Hello &amp; World",
    "Price &lt; $100 &gt; $50",
    "&quot;Quote&quot; and &#39;apos&#39;",
    "Copyright &copy; 2023",
    "Spaces&nbsp;&nbsp;&nbsp;here",
    "A&#65; B&#x42; C&#67;"
];

testCases.forEach(test => {
    console.log(`原始: ${test}`);
    console.log(`解码: ${decodeHTMLEntities(test)}`);
    console.log('---');
});

注意事项

  1. 安全性:如果处理用户输入,请确保在适当的上下文中使用解码后的内容,避免XSS攻击
  2. 性能:对于大量文本,DOMParser方法通常性能较好
  3. 兼容性:DOMParser在现代浏览器中支持良好,如果需要支持旧浏览器,可以考虑textArea方法

推荐使用第一种或第二种方法,因为它们能够处理大多数HTML实体,包括命名字符引用和数字字符引用。

相关推荐
芝士就是力量啊 ೄ೨8 分钟前
Python如何编写一个简单的类
开发语言·python
逻辑驱动的ken19 分钟前
Java高频面试考点18
java·开发语言·数据库·算法·面试·职场和发展·哈希算法
MoonBit月兔20 分钟前
「Why MoonBit 」第一期——Singularity Note AI 学习助手
开发语言·人工智能·moonbit
木木_王35 分钟前
嵌入式Linux学习 | 数据结构 (Day05) 栈与队列详解(原理 + C 语言实现 + 实战实验 + 易错点剖析)
linux·c语言·开发语言·数据结构·笔记·学习
冷雨夜中漫步1 小时前
Claude Code源码分析——Claude Code Agent Loop 详细设计文档
java·开发语言·人工智能·ai
超龄编码人1 小时前
Qt Widgets Designer QTabWidget无法添加布局
开发语言·qt
直奔標竿1 小时前
Java开发者AI转型第二十六课!Spring AI 个人知识库实战(五)——联网搜索增强实战
java·开发语言·人工智能·spring boot·后端·spring
Python大数据分析@1 小时前
CLI一键采集,使用Python搭建TikTok电商爬虫Agent
开发语言·爬虫·python
@小码农1 小时前
2026年3月Scratch图形化编程等级考试一级真题试卷
开发语言·数据结构·c++·算法
这儿有一堆花1 小时前
住宅代理(Residential Proxy)技术指南
开发语言·数据库·php