Convert tags to html entities

后端 未结 7 699
小蘑菇
小蘑菇 2020-12-08 17:16

Is it possible to convert html tags to html entities using javascript/jquery using any way possible such as regex or some other way. If yes, then how?

Exampl

7条回答
  •  隐瞒了意图╮
    2020-12-08 17:54

    I have 2 fast and small implementations for encoding HTML safely.

    You can encode all characters in your string:

    function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
    

    Or just target the main characters to worry about (&, inebreaks, <, >, " and ') like:

    function encode(r){
    return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
    }
    
    var myString='Encode HTML entities!\n"Safe" escape 
    
                                     
                  
    提交回复
热议问题