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

相关推荐
SuperEugene18 分钟前
后台权限与菜单渲染:基于路由和后端返回的几种实现方式
前端·javascript·vue.js
csdn飘逸飘逸20 分钟前
Autojs基础-全局函数与变量(globals)
javascript
KKKK30 分钟前
手写Promise,从测试用例的角度理解
javascript
青青家的小灰灰31 分钟前
迈向全栈新时代:SSR/SSG 原理、Next.js 架构与 React Server Components (RSC) 实战
前端·javascript·react.js
SuperEugene31 分钟前
弹窗与抽屉组件封装:如何做一个全局可控的 Dialog 服务
前端·javascript·vue.js
青青家的小灰灰32 分钟前
透视 React 内核:Diff 算法、合成事件与并发特性的深度解析
前端·javascript·react.js
SuperEugene34 分钟前
组合式函数 、 Hooks(Vue2 mixin 、 Vue3 composables)的实战封装
前端·javascript·vue.js
wuhen_n1 小时前
模板编译三阶段:parse-transform-generate
前端·javascript·vue.js
滕青山1 小时前
正则表达式测试 在线工具核心JS实现
前端·javascript·vue.js
不可能的是1 小时前
前端图片懒加载方案全解析
前端·javascript