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

相关推荐
Moment1 分钟前
富文本编辑器技术选型,到底是 Prosemirror 还是 Tiptap 好 ❓❓❓
前端·javascript·面试
南行*4 分钟前
C语言Linux环境编程
linux·c语言·开发语言·网络安全
xkxnq6 分钟前
第二阶段:Vue 组件化开发(第 18天)
前端·javascript·vue.js
Morwit7 分钟前
Qt qml创建c++类的单例对象
开发语言·c++·qt
晓得迷路了7 分钟前
栗子前端技术周刊第 112 期 - Rspack 1.7、2025 JS 新星榜单、HTML 状态调查...
前端·javascript·html
古城小栈9 分钟前
Rust 已经自举,却仍需GNU与MSVC工具链的缘由
开发语言·rust
怕浪猫10 分钟前
React从入门到出门 第五章 React Router 配置与原理初探
前端·javascript·react.js
jinmo_C++10 分钟前
从零开始学前端 · HTML 基础篇(一):认识 HTML 与页面结构
前端·html·状态模式
jarreyer14 分钟前
数据项目分析标准化流程
开发语言·python·机器学习
鹏多多17 分钟前
前端2025年终总结:借着AI做大做强再创辉煌
前端·javascript