Can I escape html special chars in javascript?

后端 未结 15 1607
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 02:26

I want to display a text to HTML by a javascript function. How can I escape html special chars in JS? Is there an API ?

15条回答
  •  滥情空心
    2020-11-22 03:16

    You can encode every character 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)+";"})
    }
    
    test.value=encode('How to encode\nonly html tags &<>\'" nice & fast!');
    
    /*************
    * \x26 is &ersand (it has to be first),
    * \x0A is newline,
    *************/

提交回复
热议问题