Skip to content

Instantly share code, notes, and snippets.

@martin-mok
Forked from yidas/js-encode-decode.md
Created January 11, 2020 23:08
Show Gist options
  • Save martin-mok/5b98dea77b830950b30f477bb9efa0ce to your computer and use it in GitHub Desktop.
Save martin-mok/5b98dea77b830950b30f477bb9efa0ce 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