JavaScript HTML Entities Encode & Decode ======================================== Like PHP's [htmlentities()](http://php.net/manual/en/function.htmlentities.php)/[htmlspecialchars()](http://php.net/manual/en/function.htmlspecialchars.php) functions, JavaScript is easy to implement it. Encode ------ ```javascript /** * HTML entities encode * * @param {string} str Input text * @return {string} Filtered text */ function htmlencode (str){ var div = document.createElement('div'); div.appendChild(document.createTextNode(str)); return div.innerHTML; } ``` > jQuery implementation: `return $("
").text(str).html();` --- Decode ------ ```javascript /** * HTML entities decode * * @param {string} str Input text * @return {string} Filtered text */ function htmldecode (str){ var txt = document.createElement('textarea'); txt.innerHTML = str; return txt.value; } ``` > jQuery implementation: `return $("
").html(str).text();` --- ***In general**, most Front-End development doesn't require `encode`/`decode` functions, you can evaluate your scenario to confirm the need for use.* > [Demo - JSFiddle](https://jsfiddle.net/a0v632p7/1/) > > [JavaScript nl2br & br2nl functions](https://gist.github.com/yidas/41cc9272d3dff50f3c9560fb05e7255e) > > [CSS - white-space for textarea print by MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)