Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 300
Marty Chang Avatar asked Oct 26 '16 13:10

Marty Chang


People also ask

What is HTML entity decode?

HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are encoded as &lt; and &gt; for HTTP transmission.

Can you decode HTML?

Wikipedia has a good expalanation of character encodings and how some characters should be represented in HTML. Load the HTML data to decode from a file, then press the 'Decode' button: Browse: Alternatively, type or paste in the text you want to HTML–decode, then press the 'Decode' button.


2 Answers

A nice function using es6 for escaping html:

const escapeHTML = str => str.replace(/[&<>'"]/g,    tag => ({       '&': '&amp;',       '<': '&lt;',       '>': '&gt;',       "'": '&#39;',       '"': '&quot;'     }[tag])); 
like image 164
asafel Avatar answered Sep 19 '22 12:09

asafel


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

like image 44
A. Gille Avatar answered Sep 17 '22 12:09

A. Gille