97

In JavaScript (server side NodeJS) I'm writing a program which generates XML as output.

I am building the XML by concatenating a string:

str += '<' + key + '>';
str += value;
str += '</' + key + '>';

The problem is: what if value contains characters like '&', '>' or '<'? What's the best way to escape those characters?

or is there any JavaScript library around which can escape XML entities?

1
  • The question may be also tagged NodeJS since it's partially related to also that Commented Jan 9, 2024 at 7:49

13 Answers 13

146

This might be a bit more efficient with the same outcome:

function escapeXml(unsafe) {
    return unsafe.replace(/[<>&'"]/g, function (c) {
        switch (c) {
            case '<': return '&lt;';
            case '>': return '&gt;';
            case '&': return '&amp;';
            case '\'': return '&apos;';
            case '"': return '&quot;';
        }
    });
}
Sign up to request clarification or add additional context in comments.

9 Comments

@VictorGrazi: your right, its in 49 of 50 tests the faster solution. Maybe its because its nearly 5 years younger than the accepted answer.
@Sebastian ahh, that would explain it, thanks. Look here folks ^ ^ ^ ^ this is the solution you want!!!
This strikes me as a better solution than the accepted answer, which traverses the whole string five times (serially, reducing the scope for JS engine optimisation) looking for a match against a single character; hgoebl's solution traverses the input string only once, trying to match each character to one of five conditions. The question is what is more costly: 1) traversing the string; or: 2) matching each character against 5 possible characters. My intuition is that 1) would be the more costly.
The problem with accepted answer: it creates ~5 copies of the string. When the string is long, it's a lot of work to allocate memory and later garbage collect the interim strings not really used anywhere. (Note: JavaScript strings are immutable.)
@RanLottem decoding is much more complicated if input is HTML, see Wikipedia. It's better to use a parser (XML or document).
|
137

HTML encoding is simply replacing &, ", ', < and > chars with their entity equivalents. Order matters, if you don't replace the & chars first, you'll double encode some of the entities:

if (!String.prototype.encodeHTML) {
  String.prototype.encodeHTML = function () {
    return this.replace(/&/g, '&amp;')
               .replace(/</g, '&lt;')
               .replace(/>/g, '&gt;')
               .replace(/"/g, '&quot;')
               .replace(/'/g, '&apos;');
  };
}

As @Johan B.W. de Vries pointed out, this will have issues with the tag names, I would like to clarify that I made the assumption that this was being used for the value only

Conversely if you want to decode HTML entities1, make sure you decode &amp; to & after everything else so that you don't double decode any entities:

if (!String.prototype.decodeHTML) {
  String.prototype.decodeHTML = function () {
    return this.replace(/&apos;/g, "'")
               .replace(/&quot;/g, '"')
               .replace(/&gt;/g, '>')
               .replace(/&lt;/g, '<')
               .replace(/&amp;/g, '&');
  };
}

1 just the basics, not including &copy; to © or other such things


As far as libraries are concerned. Underscore.js (or Lodash if you prefer) provides an _.escape method to perform this functionality.

9 Comments

This almost covers the 5 XML entities. Just need @apos;
This looks like it is replacing the same string over and over again which could be performance heavy when handling lots of data. Any faster alternative?
@Jonny, The regular expression is going to provide worse performance than the multiple calls to .replace(). In either case, you'd have to have a seriously huge amount of data to notice any significant issues. A faster alternative would be to benchmark your app and find the actual choke point (usually nested loops), rather than worry about something as negligible as this.
I had 100-200 lines of data in a Google Spreadsheet. I was converting that to plists (xml) and had to replace those xml entities. I wrote a custom javascript function using the above code for that. It worked, but was very slow. The spreadsheet kind of choked at times but as it is just a "do once" step the speed didn't matter in the end.
I know this answer is old, but just to make clear for newcomers to JS: attaching random functions, that are not polyfills for some standardized proposal, to global prototypes is a bad idea.
|
26

If you have jQuery, here's a simple solution:

  String.prototype.htmlEscape = function() {
    return $('<div/>').text(this.toString()).html();
  };

Use it like this:

"<foo&bar>".htmlEscape(); -> "&lt;foo&amp;bar&gt"

3 Comments

I like this technique, for its "let the browser do it" attitude. Are there any downsides, maybe other than poorer performance, as this is going through the DOM API?
Single and double quote are not escaped with this technique: $('<div/>').text('<&\'>"').html() -> "&lt;&amp;'&gt;""
Single and double quotes generally don't need to be escaped.
8

you can use the below method. I have added this in prototype for easier access. I have also used negative look-ahead so it wont mess things, if you call the method twice or more.

Usage:

 var original = "Hi&there";
 var escaped = original.EncodeXMLEscapeChars();  //Hi&amp;there

Decoding is automaticaly handeled in XML parser.

Method :

//String Extenstion to format string for xml content.
//Replces xml escape chracters to their equivalent html notation.
String.prototype.EncodeXMLEscapeChars = function () {
    var OutPut = this;
    if ($.trim(OutPut) != "") {
        OutPut = OutPut.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
        OutPut = OutPut.replace(/&(?!(amp;)|(lt;)|(gt;)|(quot;)|(#39;)|(apos;))/g, "&amp;");
        OutPut = OutPut.replace(/([^\\])((\\\\)*)\\(?![\\/{])/g, "$1\\\\$2");  //replaces odd backslash(\\) with even.
    }
    else {
        OutPut = "";
    }
    return OutPut;
};

4 Comments

Underappreciated excellent solution. Ensuring you won't wind up with the infamous &amp;amp; string in your output is beautiful.
With this code, you just edited all instances of String in all application, e.g. let a = 'foo' will be affected by this code. Better create helper function instead of extending prototype.
Please do not mutate builtin objects because it leads to conflicts and so is a very poor practice.
Regarding manipulating JS builtin objects. I agree completely that you should NEVER manipulate Object or Array but I have been writing very complex SPA's in JavaScript for 22 years and have never had issues with manipulating the String object. Eg. I have added a trim() and format() function for over 20 years with no regressions.
4

It just feels time for an update now that we have string interpolation, and a few other modernisations. And uses object lookup because it really should.

const escapeXml = (unsafe) =>
    unsafe.replace(/[<>&'"]/g, (c) => `&${({
        '<': 'lt',
        '>': 'gt',
        '&': 'amp',
        '\'': 'apos',
        '"': 'quot'
    })[c]};`);

1 Comment

I really appreciate this code-golfed solution. Very simple and concise.
2

I originally used the accepted answer in production code and found that it was actually really slow when used heavily. Here is a much faster solution (runs at over twice the speed):

   var escapeXml = (function() {
        var doc = document.implementation.createDocument("", "", null)
        var el = doc.createElement("temp");
        el.textContent = "temp";
        el = el.firstChild;
        var ser =  new XMLSerializer();
        return function(text) {
            el.nodeValue = text;
            return ser.serializeToString(el);
        };
    })();

console.log(escapeXml("<>&")); //&lt;&gt;&amp;

2 Comments

This assumes that you have document object. I don't have it.
Not possible in Node.js without using libraries like jsdom.
2

maybe you can try this,

function encodeXML(s) {
  const dom = document.createElement('div')
  dom.textContent = s
  return dom.innerHTML
}

reference

Comments

2

Caution, all the regexing isn't good if you have XML inside XML.
Instead loop over the string once, and substitute all escape characters.
That way, you can't run over the same character twice.

function _xmlAttributeEscape(inputString)
{
    var output = [];

    for (var i = 0; i < inputString.length; ++i)
    {
        switch (inputString[i])
        {
            case '&':
                output.push("&amp;");
                break;
            case '"':
                output.push("&quot;");
                break;
            case "<":
                output.push("&lt;");
                break;
            case ">":
                output.push("&gt;");
                break;
            default:
                output.push(inputString[i]);
        }


    }

    return output.join("");
}

1 Comment

Your observation about XML inside XML seems right to me. Being rigourous, you would want to re-escape ampersands of existing entities (eg. &amp;amp;) if you don't want them to break up when decoded.
1

Adding on to ZZZZBov's answer, I find this a bit cleaner and easier to read:

const encodeXML = (str) =>
    str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&apos;');

Additionally, all five characters can be found here for example: https://www.sitemaps.org/protocol.html

Note that this only encodes values (as other have stated).

Comments

1

if something is escaped from before, you could try this since this will not double escape like many others

function escape(text) {
    return String(text).replace(/(['"<>&'])(\w+;)?/g, (match, char, escaped) => {
        if(escaped) {
            return match;
        }
        
        switch(char) {
            case '\'': return '&apos;';
            case '"': return '&quot;';
            case '<': return '&lt;';
            case '>': return '&gt;';
            case '&': return '&amp;';
        }
    });
}

2 Comments

@ValerioBozz the case condition and the return value pair are mismatched. &quot; is for double quotes (“) and &apos; is for single quotes (‘).
Ah good catch, nice. I've proposed an edit.
0

Technically, &, < and > aren't valid XML entity name characters. If you can't trust the key variable, you should filter them out.

If you want them escaped as HTML entities, you could use something like http://www.strictly-software.com/htmlencode .

Comments

0

Faced to a similar problem, but on the client side for HTML, I found it easier to use the DOM instead of manipulating raw HTML.

let node=document.createTextNode(myTextToEscape);

The createTextNode function also exists for XML DOM API (e.g. xmldom package for node.js).

To get the “XML source code” of the node, you can add it to an element and call innerHTML on the element or alternatively you can use an XMLSerializer object.

let myXmlCode=new XMLSerializer().serializeToString(node);

Comments

-2

This is simple:

sText = ("" + sText).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");

5 Comments

in what world is this 'simple' compared to the replace methods above?
Simple to write, I didn't say that it was simpler compared to those above. It is just different
I'm stumped trying to think of a worse solution
@developerbmw if you don't want to add a method and don't use jquery, this is one of the best solutions
@developerbmw for readability, sometimes it's better to write code i a way that enable reading functionality from top to down. Dynamic languages is very easy to make unreadable fast. It depends on the situation. Also using components that is used in different scenarios and need its own logic. A small component may not need functions if logic is only being used in one method. I am a C++ developer and have been coding a lot of C. C is very easy to read and if you know why then you know my argument on this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.