【问题标题】:Alternative to replace all html entities by characters in Web Worker用 Web Worker 中的字符替换所有 html 实体的替代方法
【发布时间】:2021-02-11 20:15:28
【问题描述】:

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

【问题讨论】:

    标签: javascript web-worker jquery-terminal


    【解决方案1】:

    我的解决方案是访问显示所有 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;
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-14
      • 2012-12-29
      • 2023-03-11
      • 2019-03-20
      • 2018-10-21
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      相关资源
      最近更新 更多