HTML Encode e Decode in Vanilla JavaScript
Un esempio di come codificare e decodificare una stringa in html usando JavaScript puro.
Ci sono due funzioni sgart.htmlEncode(str) e sgart.htmlDecode(str):
che possono essere usate in questo modo:
Ci sono due funzioni sgart.htmlEncode(str) e sgart.htmlDecode(str):
JavaScript
var sgart = sgart || {};
sgart.htmlEncode = function (str) {
if (!sgart.__htmlEncodeDecode_DIV) {
sgart.__htmlEncodeDecode_DIV = document.createElement("div");
sgart.__htmlEncodeDecode_DIV_textContent_enabled = "textContent" in sgart.__htmlEncodeDecode_DIV;
}
if (sgart.__htmlEncodeDecode_DIV_textContent_enabled) {
sgart.__htmlEncodeDecode_DIV.textContent = str;
} else {
sgart.__htmlEncodeDecode_DIV.innerText = str;
}
return sgart.__htmlEncodeDecode_DIV.innerHTML;
};
sgart.htmlDecode = function (str) {
if (!sgart.__htmlEncodeDecode_DIV) {
sgart.__htmlEncodeDecode_DIV = document.createElement("div");
sgart.__htmlEncodeDecode_DIV_textContent_enabled = "textContent" in sgart.__htmlEncodeDecode_DIV;
}
sgart.__htmlEncodeDecode_DIV.innerHTML = str;
return sgart.__htmlEncodeDecode_DIV_textContent_enabled ? sgart.__htmlEncodeDecode_DIV.textContent : sgart.__htmlEncodeDecode_DIV.innerText;
};
JavaScript
sgart.htmlEncode("<div style=\"border:0\">"); // <div style="border:0">
sgart.htmlDecode("<div style=\"border:0\">"); // <div style="border:0">