admin管理员组文章数量:1134589
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 += '<' + key + '>';
str += value;
str += '</' + key + '>';
The problem is: what if value
contains characters like '&'
, '>'
or '<'
?
What's the best way to escape those characters?
or is there any JavaScript library around which can escape XML entities?
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 += '<' + key + '>';
str += value;
str += '</' + key + '>';
The problem is: what if value
contains characters like '&'
, '>'
or '<'
?
What's the best way to escape those characters?
or is there any JavaScript library around which can escape XML entities?
Share Improve this question edited Jan 9, 2024 at 21:06 Valerio Bozz 1,44422 silver badges36 bronze badges asked Oct 27, 2011 at 16:04 Zo72Zo72 15.3k18 gold badges74 silver badges105 bronze badges 1- The question may be also tagged NodeJS since it's partially related to also that – Valerio Bozz Commented Jan 9, 2024 at 7:49
12 Answers
Reset to default 143This 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 '"';
}
});
}
HTML encoding is simply replacing &
, "
, '
, <
and >
chars with their entity equivalents. Order matters, if you don't replace the &
chars first, you'll double encode some of the entities:
if (!String.prototype.encodeHTML) {
String.prototype.encodeHTML = function () {
return this.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};
}
As @Johan B.W. de Vries pointed out, this will have issues with the tag names, I would like to clarify that I made the assumption that this was being used for the value
only
Conversely if you want to decode HTML entities1, make sure you decode &
to &
after everything else so that you don't double decode any entities:
if (!String.prototype.decodeHTML) {
String.prototype.decodeHTML = function () {
return this.replace(/'/g, "'")
.replace(/"/g, '"')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/&/g, '&');
};
}
1 just the basics, not including ©
to ©
or other such things
As far as libraries are concerned. Underscore.js (or Lodash if you prefer) provides an _.escape
method to perform this functionality.
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>"
you can use the below method. I have added this in prototype for easier access. I have also used negative look-ahead so it wont mess things, if you call the method twice or more.
Usage:
var original = "Hi&there";
var escaped = original.EncodeXMLEscapeChars(); //Hi&there
Decoding is automaticaly handeled in XML parser.
Method :
//String Extenstion to format string for xml content.
//Replces xml escape chracters to their equivalent html notation.
String.prototype.EncodeXMLEscapeChars = function () {
var OutPut = this;
if ($.trim(OutPut) != "") {
OutPut = OutPut.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
OutPut = OutPut.replace(/&(?!(amp;)|(lt;)|(gt;)|(quot;)|(#39;)|(apos;))/g, "&");
OutPut = OutPut.replace(/([^\\])((\\\\)*)\\(?![\\/{])/g, "$1\\\\$2"); //replaces odd backslash(\\) with even.
}
else {
OutPut = "";
}
return OutPut;
};
It just feels time for an update now that we have string interpolation, and a few other modernisations. And uses object lookup because it really should.
const escapeXml = (unsafe) =>
unsafe.replace(/[<>&'"]/g, (c) => `&${({
'<': 'lt',
'>': 'gt',
'&': 'amp',
'\'': 'apos',
'"': 'quot'
})[c]};`);
I originally used the accepted answer in production code and found that it was actually really slow when used heavily. Here is a much faster solution (runs at over twice the speed):
var escapeXml = (function() {
var doc = document.implementation.createDocument("", "", null)
var el = doc.createElement("temp");
el.textContent = "temp";
el = el.firstChild;
var ser = new XMLSerializer();
return function(text) {
el.nodeValue = text;
return ser.serializeToString(el);
};
})();
console.log(escapeXml("<>&")); //<>&
maybe you can try this,
function encodeXML(s) {
const dom = document.createElement('div')
dom.textContent = s
return dom.innerHTML
}
reference
Caution, all the regexing isn't good if you have XML inside XML.
Instead loop over the string once, and substitute all escape characters.
That way, you can't run over the same character twice.
function _xmlAttributeEscape(inputString)
{
var output = [];
for (var i = 0; i < inputString.length; ++i)
{
switch (inputString[i])
{
case '&':
output.push("&");
break;
case '"':
output.push(""");
break;
case "<":
output.push("<");
break;
case ">":
output.push(">");
break;
default:
output.push(inputString[i]);
}
}
return output.join("");
}
Adding on to ZZZZBov's answer, I find this a bit cleaner and easier to read:
const encodeXML = (str) =>
str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
Additionally, all five characters can be found here for example: https://www.sitemaps.org/protocol.html
Note that this only encodes values (as other have stated).
Technically, &, < and > aren't valid XML entity name characters. If you can't trust the key variable, you should filter them out.
If you want them escaped as HTML entities, you could use something like http://www.strictly-software.com/htmlencode .
if something is escaped from before, you could try this since this will not double escape like many others
function escape(text) {
return String(text).replace(/(['"<>&'])(\w+;)?/g, (match, char, escaped) => {
if(escaped) {
return match;
}
switch(char) {
case '\'': return ''';
case '"': return '"';
case '<': return '<';
case '>': return '>';
case '&': return '&';
}
});
}
This is simple:
sText = ("" + sText).split("<").join("<").split(">").join(">").split('"').join(""").split("'").join("'");
本文标签: How to escape XML entities in JavaScriptStack Overflow
版权声明:本文标题:How to escape XML entities in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736781051a1952598.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论