我想通过JavaScript函数将文本显示为HTML。如何在JavaScript中转义HTML特殊字符?有API吗?


当前回答

照章办事

OWASP建议“[e]除字母数字字符外,[您应该]转义所有ASCII值小于256的字符,使用&#xHH;格式(或命名实体,如果可用),以防止切换[一个]属性。

这里有一个函数可以做到这一点,并有一个用法示例:

不安全功能 return键unsafe replace(。 - [u0000 - u002F \ u003A \ u0040 u005B - u0060 \ u007B \ u00FF] / g, c => '&#' + (' 1000 +。’这是c . charCodeAt(+ 0)。切片(四)?” ) 的 querySelector(“div”)的文件。innerHTML = <span class= + escapeHTML(' faeclass ' onclick="alert " ("test") + > +。’” escapeHTML(“<脚本>alert”(“attributes检查员”)\u003C/脚本>' ”< /跨越> < div > < / div >

您应该亲自验证我提供的实体范围,以验证函数的安全性。你也可以使用这个正则表达式,它具有更好的可读性,应该涵盖相同的字符代码,但在我的浏览器中性能下降了10%:

/(?![0-9A-for-z])[\u0000-\u00FF]/g

其他回答

我想出了这个解决方案。

假设我们想向元素添加一些HTML,其中包含来自用户或数据库的不安全数据。

var unsafe = 'some unsafe data like <script>alert("oops");</script> here';

var html = '';
html += '<div>';
html += '<p>' + unsafe + '</p>';
html += '</div>';

element.html(html);

它对于XSS攻击是不安全的。现在加上这个: $ (document.createElement (div)) . html(不安全)。text ();

就是这样

var unsafe = 'some unsafe data like <script>alert("oops");</script> here';

var html = '';
html += '<div>';
html += '<p>' + $(document.createElement('div')).html(unsafe).text(); + '</p>';
html += '</div>';

element.html(html);

对我来说,这比使用.replace()容易得多,它会删除!!所有可能的HTML标签(我希望)。

找到一个更好的解决方案是很有趣的:

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

我没有解析>,因为它没有破坏结果中的XML/HTML代码。

以下是基准测试:http://jsperf.com/regexpairs 此外,我还创建了一个通用转义函数:http://jsperf.com/regexpairs2

你可以对字符串中的每个字符进行编码:

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

或者只关注主要角色(&,inebreaks, <, >, "和'),比如:

函数编码(r) { 返回r.replace (/ [\ x26 \ x0A \ < > "] / g函数(r){返回" & # + r.charCodeAt(0) +”;“}) } 测试。value=encode('如何编码\nonly html标签&<>\'" nice & fast!'); /************* * \x26是& &号(必须排在第一位), * \x0A为换行符, *************/ < textarea测试行id = =“9”关口= " 55 " > & # 119;& # 119;& # 119;& # 46;& # 87;& # 72;& # 65;& # 75;& # 46;& # 99;& # 111;& # 109;textarea > < /

在JavaScript中删除字符串中的HTML标签:

const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");

console.log(strippedString);

使用Lodash:

_.escape('fred, barney, & pebbles');
// => 'fred, barney, &amp; pebbles'

源代码