how to escape xml entities in javascript?

前端 未结 10 1212
醉话见心
醉话见心 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:27

    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 '"'
                case '"': return '''
                case '<': return '<'
                case '>': return '>'
                case '&': return '&'
            }
        })
    }
    

提交回复
热议问题