Last active
January 13, 2020 14:26
-
-
Save mootoh/5131361 to your computer and use it in GitHub Desktop.
XML escape function in Javascript.
This file contains hidden or 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
// original: | |
// - http://stackoverflow.com/questions/7918868/how-to-escape-xml-entities-in-javascript | |
// - http://stackoverflow.com/questions/1091945/where-can-i-get-a-list-of-the-xml-document-escape-characters | |
// - http://www.w3.org/TR/xml/#syntax | |
if (!String.prototype.encodeXML) { | |
String.prototype.encodeXML = function () { | |
return this.replace(/&/g, '&') | |
.replace(/</g, '<') | |
.replace(/>/g, '>') | |
.replace(/'/g, ''') | |
.replace(/"/g, '"'); | |
}; | |
} |
It would also escape the "&" characters of already escaped characters, such as: '& amp ;'.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this will only replace the first occurrence of the chareacter. Better way to do this
this.replace(new RegExp(search, 'g'), replacement);
orthis.split(search).join(replacement);