Skip to content

Instantly share code, notes, and snippets.

@panzi
Forked from atesgoral/escapeXml.js
Created February 18, 2012 04:16
Show Gist options
  • Save panzi/1857360 to your computer and use it in GitHub Desktop.
Save panzi/1857360 to your computer and use it in GitHub Desktop.
Escape XML in JavaScript.
var XML_CHAR_MAP = {
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
'"': '&quot;',
"'": '&apos;'
};
function escapeXml (s) {
return s.replace(/[<>&"']/g, function (ch) {
return XML_CHAR_MAP[ch];
});
}
var HTML_CHAR_MAP = {
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
'"': '&quot;',
"'": '&#39;'
};
function escapeHtml (s) {
return s.replace(/[<>&"']/g, function (ch) {
return HTML_CHAR_MAP[ch];
});
}
@panzi
Copy link
Author

panzi commented Apr 30, 2012

escapeXml escapes XML, but not HTML because HTML does not know &apos;. However most browsers also support &apos; in HTML documents. IE is not most browsers.

@ststeiger
Copy link

@panzi: Which is true for &apos; for IE <= 8, but it is supported from IE9+ (that little peculiarity hit me hard once).

@ststeiger
Copy link

In XML 1.1, you can do it far simpler:

var str = "Hello World äöü ÄÖÜäöüàéèâêû'áéóñ";

var output = [];
for(var i = 0; i < str.length; ++i)

{
// http://www.w3schools.com/jsref/jsref_charCodeAt.asp
output.push("&#" + str.charCodeAt(i) + ";");
}

console.log(output.join("")); // ==> hello

DECLARE @x as XML
SET @x = (SELECT CAST('<x>' + 'Hello World äöü ÄÖÜäöüàéèâêû'áéóñ' + '</x>' AS xml))

SELECT @x.value('.[1]', 'nvarchar(MAX)')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment