Like PHP's htmlentities()/htmlspecialchars() functions, JavaScript is easy to implement it.
/**
* 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();
/**
* 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.
Thank you very much this helped with my massive project!