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

相关推荐
im_AMBER2 小时前
React 12
前端·javascript·笔记·学习·react.js·前端框架
开开心心就好2 小时前
电脑音质提升:杜比全景声安装详细教程
java·开发语言·前端·数据库·电脑·ruby·1024程序员节
t198751282 小时前
基于多假设跟踪(MHT)算法的MATLAB实现
开发语言·matlab
跟着珅聪学java2 小时前
在Java中判断Word文档中是否包含表格并读取表格内容,可以使用Apache POI库教程
java·开发语言·word
午安~婉2 小时前
HTML CSS八股
前端·css·html
我也要当昏君3 小时前
5.3 【2012统考真题】
开发语言·智能路由器·php
前端付豪3 小时前
Vue 中的 JSX:让组件渲染更灵活的正确方式
前端·javascript·vue.js
初见无风3 小时前
3.4 Boost库intrusive_ptr智能指针的使用
开发语言·boost