在 Web Worker 中用字符替换所有 html 实体的替代方法

Alternative to replace all html entities by characters in Web Worker

我正在尝试将我的脚本(jQuery 终端库)添加到 Web Worker 中的 运行,只需要最少的 jQuery 替换且没有 JS-DOM。我有 bare_text 个这样的函数:

// -------------------------------------------------------------------------
function bare_text(string) {
    if (!string.match(/&/)) {
        return string;
    }
    return $('<span>' + safe(string) + '</span>').text();
}
// -------------------------------------------------------------------------
function text(string) {
    return bare_text($.terminal.strip(string));
}
// -------------------------------------------------------------------------
function safe(string) {
    if (!string.match(/[<>&]/)) {
        return string;
    }
    return string.replace(/&(?![^;]+;)/g, '&amp;')
        .replace(/>/g, '&gt;').replace(/</g, '&lt;');
}

我需要更改此功能以执行相同但没有 DOM 和 jQuery。有什么选择吗?

此外,如果您知道如何以其他方式简化这些功能,我将非常感激。那么这些函数的作用(代码很旧)它用适当的字符替换任何 html 实体,并忽略被视为普通文本的 html 标签。

我的解决方案是访问显示所有 html 实体的网站(示例:https://www.freeformatter.com/html-entities.html

和运行控制台中的这段代码:

[].concat.apply([], [...document.querySelectorAll('.bordered-table')].map(table => {
    var t = [...table.querySelectorAll('tbody tr')];
    return t.map(tr => ({
      entity: tr.querySelector('td:nth-child(2)').innerText,
      char: tr.querySelector('td:nth-child(1)').innerText
    })).filter(o => o.entity);
})).reduce((acc, obj) => (acc[obj.entity] = obj.code, acc), {});

然后您可以使用 JSON.stringify(arr, true, 4); 将其转换为字符串 您可以 copy/paste 到您的代码中并像这样使用:

var entities = {...}; // map from above

function renderEntities(str) {
    return str.replace(/&#(x?)([0-9]+);/g, function(_, hex, code) {
        code = parseInt(code, hex ? 16 : 10);
        return String.fromCharCode(code);
    }).replace(/(&[^;]+;)/g, function(_, entity) {
        // if entity is not recognized it need to be
        // inserted as is example &foo;
        return entities[entity] || entity;
    });
}