Instantly share code, notes, and snippets.

Embed
What would you like to do?
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