how to escape xml entities in javascript?

前端 未结 10 1108
醉话见心
醉话见心 2020-11-27 14:51

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 += \'&l         


        
相关标签:
10条回答
  • 2020-11-27 15:32

    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;';
            }
        });
    }
    
    0 讨论(0)
  • 2020-11-27 15:36

    This is simple:

    sText = ("" + sText).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");
    
    0 讨论(0)
  • 2020-11-27 15:37

    maybe you can try this,

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

    reference

    0 讨论(0)
  • 2020-11-27 15:39

    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"

    0 讨论(0)
提交回复
热议问题