HtmlSpecialChars equivalent in Javascript?

后端 未结 16 1907
耶瑟儿~
耶瑟儿~ 2020-11-22 06:00

Apparently, this is harder to find than I thought it would be. And it even is so simple...

Is there a function equivalent to PHP\'s htmlspecialchars built into Javas

16条回答
  •  佛祖请我去吃肉
    2020-11-22 06:35

    Worth a read: http://bigdingus.com/2007/12/29/html-escaping-in-javascript/

    escapeHTML: (function() {
     var MAP = {
       '&': '&',
       '<': '<',
       '>': '>',
       '"': '"',
       "'": '''
     };
      var repl = function(c) { return MAP[c]; };
      return function(s) {
        return s.replace(/[&<>'"]/g, repl);
      };
    })()
    

    Note: Only run this once. And don't run it on already encoded strings e.g. & becomes &amp;

提交回复
热议问题