Is there any way to encode or decode HTML objects using JavaScript or ES6? For example, < will be encoded as < . There are libraries like html-entities for Node.js, but it looks like there should be something built into JavaScript in JavaScript that already addresses this common need.
<
<
html-entities
There is no built-in function in the JavaScript API that converts ASCII characters to the equivalent of "html-entity". Here is the beginning of the solution and a simple trick you might like
A nice feature using es6 to exit HTML:
const escapeHTML = str => str.replace(/[&<>'"]/g, tag => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' }[tag] || tag));
To decode html, I just use the <pre> and this function:
<pre>
function convertHTML(str) { var entityPairs = [ {character: '&', html: '&'}, {character: '<', html: '<'}, {character: '>', html: '>'}, {character: "'", html: '''}, {character: '"', html: '"'}, ]; entityPairs.forEach(function(pair){ var reg = new RegExp(pair.character, 'g'); str = str.replace(reg, pair.html); }); return str; } //var or file.html from Ajax var str = ` <head> <title>OK</title> </head>`; document.getElementById("preHtml").innerHTML = convertHTML(str);
<pre id="preHtml"></pre>
For pure JS without a library, you can encode and decode HTML objects using pure Javascript , for example:
let encode = str => { let buf = []; for (var i = str.length - 1; i >= 0; i--) { buf.unshift(['&#', str[i].charCodeAt(), ';'].join('')); } return buf.join(''); } let decode = str => { return str.replace(/&#(\d+);/g, function(match, dec) { return String.fromCharCode(dec); }); }
Usages :
encode("Hello > ยฉ <") // "Hello > © <" decode("Hello > © © <") // "Hello > © ยฉ <"
However, you can see that this approach has a couple of disadvantages:
H
H
>
Usage :
he.encode('foo ยฉ bar โ baz ๐ qux'); // Output : 'foo © bar ≠ baz 𝌆 qux' he.decode('foo © bar ≠ baz 𝌆 qux'); // Output : 'foo ยฉ bar โ baz ๐ qux'