Can I escape html special chars in javascript?

后端 未结 15 1426
隐瞒了意图╮
隐瞒了意图╮ 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:07

    It was interesting to find a better solution:

    var escapeHTML = function(unsafe) {
      return unsafe.replace(/[&<"']/g, function(m) {
        switch (m) {
          case '&':
            return '&';
          case '<':
            return '<';
          case '"':
            return '"';
          default:
            return ''';
        }
      });
    };
    

    I do not parse > because it does not break XML/HTML code in the result.

    Here are the benchmarks: http://jsperf.com/regexpairs Also, I created a universal escape function: http://jsperf.com/regexpairs2

提交回复
热议问题