HtmlSpecialChars equivalent in Javascript?

后端 未结 16 1507
耶瑟儿~
耶瑟儿~ 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:17

    There is a problem with your solution code--it will only escape the first occurrence of each special character. For example:

    escapeHtml('Kip\'s evil "test" code\'s here');
    Actual:   Kip's <b>evil "test" code's here
    Expected: Kip's <b>evil</b> "test" code's here
    

    Here is code that works properly:

    function escapeHtml(text) {
      return text
          .replace(/&/g, "&")
          .replace(//g, ">")
          .replace(/"/g, """)
          .replace(/'/g, "'");
    }
    

    Update

    The following code will produce identical results to the above, but it performs better, particularly on large blocks of text (thanks jbo5112).

    function escapeHtml(text) {
      var map = {
        '&': '&',
        '<': '<',
        '>': '>',
        '"': '"',
        "'": '''
      };
      
      return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    

提交回复
热议问题