I'm trying to get my script (jQuery Terminal library) to run in Web Worker with minimal jQuery replacement and no JS-DOM. I have bare_text
functions like this:
// -------------------------------------------------------------------------
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, '&')
.replace(/>/g, '>').replace(/</g, '<');
}
I need to change this function to do the same but without DOM and jQuery. Any options?
Also if you know how to simplify the other way those functions I would be very thankful. So what those functions do (the code is very old) it replace any html entities with proper characters and it ignore html tags that are treated as normal text.
My solution was to go to website that show all html entites (example: https://www.freeformatter.com/html-entities.html)
and run this code in console:
[].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), {});
then you can convert that to string using JSON.stringify(arr, true, 4);
you can copy/paste into your code and use like this:
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;
});
}