how to escape xml entities in javascript?

2020-01-26 05:12发布

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?

标签: javascript
9条回答
兄弟一词,经得起流年.
2楼-- · 2020-01-26 05:36

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;
};
查看更多
神经病院院长
3楼-- · 2020-01-26 05:38

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;
查看更多
够拽才男人
4楼-- · 2020-01-26 05:40

maybe you can try this,

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

reference

查看更多
登录 后发表回答