Skip to content

Instantly share code, notes, and snippets.

@sheraz-haider
Forked from yidas/js-encode-decode.md
Created August 3, 2021 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sheraz-haider/52b481e102a33a269961488c6af5098d to your computer and use it in GitHub Desktop.
Save sheraz-haider/52b481e102a33a269961488c6af5098d to your computer and use it in GitHub Desktop.
JavaScript HTML Entities Encode & Decode

JavaScript HTML Entities Encode & Decode

Like PHP's htmlentities()/htmlspecialchars() functions, JavaScript is easy to implement it.

Encode

/**
 * 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 $("<div/>").text(str).html();


Decode

/**
 * 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 $("<div/>").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

JavaScript nl2br & br2nl functions

CSS - white-space for textarea print by MDN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment