How to add special characters like & > in XML file using JavaScript

By | January 12, 2018

I am generating XML using Javascript. It works fine if there are no special characters in the XML. Otherwise, it will generate this message: “invalid xml”.

I tried to replace some special characters, like:

//but it doesn't work.

For example:

<category label='ARR Builders & Developers'>



Consider generating the XML using DOM methods. For example:

var c = document.createElement("category");
c.setAttribute("label", "ARR Builders & Developers");
var s = new XMLSerializer().serializeToString(c);
s; // => "<category label=\"ARR Builder &amp; Developers\"></category>"

This strategy should avoid the XML entity escaping problems you mention but might have some cross-browser issues.


This will do the replacement in JavaScript:

xml = xml.replace(/</g, "&lt;");
xml = xml.replace(/>/g, "&gt;");

This uses regular expression literals to replace all less than and greater than symbols with their escaped equivalent.


JavaScript comes with a powerful replace() method for string objects.

In general – and basic – terms, it works this way:

var myString = yourString.replace([regular expression or simple string], [replacement string]);

The first argument to .replace() method is the portion of the original string that you wish to replace. It can be represented by either a plain string object (even literal) or a regular expression.

The regular expression is obviously the most powerful way to select a substring.

The second argument is the string object (even literal) that you want to provide as a replacement.

In your case, the replacement operation should look as follows:

//this time it should work.

Notice the first replacement operation is the ampersand, as if you should try to replace it later you would screw up pre-existing well-quoted entities for sure, just as "&amp;gt;".

In addition, pay attention to the regex ‘g’ flag, as with it the replacement will take place all throughout your text, not only on the first match.

I used regular expressions, but for simple replacements like these also plain strings would be a perfect fit.

You can find a complete reference for String.replace() here.

Leave a Reply

Your email address will not be published. Required fields are marked *