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

Marty Chang picture Marty Chang · Oct 26, 2016 · Viewed 25.3k times · Source

Is there a native way to encode or decode HTML entities using JavaScript or ES6? For example, < would be encoded as &lt;. There are libraries like html-entities for Node.js but it feels like there should be something built into JavaScript that already handles this common need.

Answer

asafel picture asafel · Aug 11, 2019

A nice function using es6 for escaping html:

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