Fastest method to escape HTML tags as HTML entities?

前端 未结 12 1640
-上瘾入骨i
-上瘾入骨i 2020-11-22 09:24

I\'m writing a Chrome extension that involves doing a lot of the following job: sanitizing strings that might contain HTML tags, by converting

12条回答
  •  醉话见心
    2020-11-22 09:43

    function encode(r) {
      return r.replace(/[\x26\x0A\x3c\x3e\x22\x27]/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,
     \x22 is ",
     \x27 is ',
     \x3c is <,
     \x3e is >
    */

提交回复
热议问题