Decode HTML objects in JavaScript?

Conversion Examples:

& -> `&` > -> `>` 

Any little library function that can handle this?

+7
javascript html html-entities
source share
3 answers

In my utility belt, this tiny function is always:

 function htmlDecode(input){ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes[0].nodeValue; } htmlDecode("&"); // "&" htmlDecode(">"); // ">" 

It will work for all HTML objects .

Edit: Since you are not in a DOM environment, I think you will have to do this using the β€œhard” way:

 function htmlDecode (input) { return input.replace(/&amp;/g, "&") .replace(/&lt;/g, "<") .replace(/&gt;/g, ">"); //... } 

If you don't like tethered replacements, you can create an object to store your objects, for example:

 function htmlDecode (input) { var entities= { "&amp;": "&", "&lt;": "<", "&gt;": ">" //.... }; for (var prop in entities) { if (entities.hasOwnProperty(prop)) { input = input.replace(new RegExp(prop, "g"), entities[prop]); } } return input; } 
+22
source share

It looks like it will do:

 function html_entity_decode(s) { var t=document.createElement('textarea'); t.innerHTML = s; var v = t.value; t.parentNode.removeChild(t); return v; } 

A source

+3
source share

Reliable encoder / decoder of HTML objects written in JavaScript.

https://mths.be/he

he (for "HTML entities") is a robust encoder / decoder of HTML objects written in JavaScript. It supports all standardized named characters in accordance with HTML , handles ambiguous ampersands and other boundary cases like a browser , has an extensive set of tests and, contrary to many other JavaScript solutions, it copes with Unicode astral characters perfectly. An online demo is available .

+1
source share

All Articles