在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实体,包括命名字符引用和数字字符引用。

相关推荐
身如柳絮随风扬9 小时前
Java中的CAS机制详解
java·开发语言
韩立学长10 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
东东51611 小时前
智能社区管理系统的设计与实现ssm+vue
前端·javascript·vue.js·毕业设计·毕设
froginwe1111 小时前
Scala 循环
开发语言
catino11 小时前
图片、文件的预览
前端·javascript
m0_7066532311 小时前
C++编译期数组操作
开发语言·c++·算法
故事和你9111 小时前
sdut-Java面向对象-06 继承和多态、抽象类和接口(函数题:10-18题)
java·开发语言·算法·面向对象·基础语法·继承和多态·抽象类和接口
Bruk.Liu11 小时前
(LangChain实战2):LangChain消息(message)的使用
开发语言·langchain
qq_4232339011 小时前
C++与Python混合编程实战
开发语言·c++·算法
m0_7155753412 小时前
分布式任务调度系统
开发语言·c++·算法