Skip to content

Instantly share code, notes, and snippets.

@mootoh
Last active January 13, 2020 14:26
Show Gist options
  • Save mootoh/5131361 to your computer and use it in GitHub Desktop.
Save mootoh/5131361 to your computer and use it in GitHub Desktop.
XML escape function in Javascript.
// 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, '&lt;')
.replace(/>/g, '&gt;')
.replace(/'/g, '&apos;')
.replace(/"/g, '&quot;');
};
}
@MajklDovi
Copy link

this will only replace the first occurrence of the chareacter. Better way to do this this.replace(new RegExp(search, 'g'), replacement); or this.split(search).join(replacement);

@gditoro
Copy link

gditoro commented Jan 13, 2020

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