In JavaScript (server side nodejs) I\'m writing a program which generates xml as output.
I am building the xml by concatenating a string:
str += \'&l
This might be a bit more efficient with the same outcome:
function escapeXml(unsafe) {
return unsafe.replace(/[<>&'"]/g, function (c) {
switch (c) {
case '<': return '<';
case '>': return '>';
case '&': return '&';
case '\'': return ''';
case '"': return '"';
}
});
}
This is simple:
sText = ("" + sText).split("<").join("<").split(">").join(">").split('"').join(""").split("'").join("'");
maybe you can try this,
function encodeXML(s) {
const dom = document.createElement('div')
dom.textContent = s
return dom.innerHTML
}
reference
If you have jQuery, here's a simple solution:
String.prototype.htmlEscape = function() {
return $('<div/>').text(this.toString()).html();
};
Use it like this:
"<foo&bar>".htmlEscape();
-> "<foo&bar>"