let p = '<h1>escapeForHTML<h1>';
let regex = /[<&]/gi;
let r = {
'>' : '>',
'&' : '&',
'<' : '<',
}
let f = function(c){
return r[c];
}
Comparer le résultat des deux écritures :
document.body.insertAdjacentHTML("afterbegin",p);
document.body.insertAdjacentHTML("afterbegin",p.replace(regex,f));
Version compacte !
const escapeForHTML = s => s.replace(/[&<]/g, c => c === '&' ? '&' : '<');
document.body.insertAdjacentHTML("afterbegin",escapeForHTML("<h1> escapeForHTML </h1>"));
document.body.insertAdjacentHTML("afterbegin","<h1> escapeForHTML </h1>");
Version avec Map
let p = '<h1>escapeForHTML<h1>';
let regex = /[<>&]/gi;
let r = new Map([
['>','>'],
['&','&'],
['<', '<'],
]);
let f = c => r.get(c)
document.body.insertAdjacentHTML("afterbegin",p);
document.body.insertAdjacentHTML("afterbegin",p.replace(regex,f));