-
-
Save panzi/1857360 to your computer and use it in GitHub Desktop.
Escape XML in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var XML_CHAR_MAP = { | |
'<': '<', | |
'>': '>', | |
'&': '&', | |
'"': '"', | |
"'": ''' | |
}; | |
function escapeXml (s) { | |
return s.replace(/[<>&"']/g, function (ch) { | |
return XML_CHAR_MAP[ch]; | |
}); | |
} | |
var HTML_CHAR_MAP = { | |
'<': '<', | |
'>': '>', | |
'&': '&', | |
'"': '"', | |
"'": ''' | |
}; | |
function escapeHtml (s) { | |
return s.replace(/[<>&"']/g, function (ch) { | |
return HTML_CHAR_MAP[ch]; | |
}); | |
} |
@panzi: Which is true for ' for IE <= 8, but it is supported from IE9+ (that little peculiarity hit me hard once).
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
escapeXml
escapes XML, but not HTML because HTML does not know'
. However most browsers also support'
in HTML documents. IE is not most browsers.