Native JavaScript or ES6 way to encode and decode HTML entities? Native JavaScript or ES6 way to encode and decode HTML entities? javascript javascript

Native JavaScript or ES6 way to encode and decode HTML entities?


A nice function using es6 for escaping html:

const escapeHTML = str => str.replace(/[&<>'"]/g,   tag => ({      '&': '&',      '<': '<',      '>': '>',      "'": '&#39;',      '"': '"'    }[tag]));


There is no native function in the JavaScript API that convert ASCII characters to their "html-entities" equivalent.Here is a beginning of a solution and an easy trick that you may like


Roll Your Own (caveat - use HE instead for most use cases)

For pure JS without a lib, you can Encode and Decode HTML entities using pure Javascript like this:

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 > © <") // "&#72;&#101;&#108;&#108;&#111;&#32;&#62;&#32;&#169;&#32;&#60;"decode("Hello > © &#169; <") // "Hello > © © <"

However, you can see this approach has a couple shortcomings:


Use the HE Library (Html Entities)

Usage:

he.encode('foo © bar ≠ baz 𝌆 qux'); // Output : 'foo &#xA9; bar &#x2260; baz &#x1D306; qux'he.decode('foo © bar ≠ baz &#x1D306; qux');// Output : 'foo © bar ≠ baz 𝌆 qux'

Related Questions