0

我试图让我的脚本(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 标记。

4

1 回答 1

0

我的解决方案是访问显示所有 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);复制/粘贴到您的代码中并像这样使用:

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;
    });
}
于 2021-02-13T07:56:56.657 回答