JavaScript 中的 HtmlSpecialChars 等价物是什么? [英] What is the HtmlSpecialChars equivalent in JavaScript?

查看:47
本文介绍了JavaScript 中的 HtmlSpecialChars 等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,这比我想象的更难找到.它甚至是那么简单...

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

是否有与 PHP 的 htmlspecialchars 等价的函数内置于 JavaScript 中?我知道自己实现它相当容易,但使用内置函数(如果可用)更好.

Is there a function equivalent to PHP's htmlspecialchars built into JavaScript? I know it's fairly easy to implement that yourself, but using a built-in function, if available, is just nicer.

对于那些不熟悉 PHP 的人,htmlspecialchars 将诸如 <htmltag/> 之类的东西翻译成 &lt;htmltag/&gt;

For those unfamiliar with PHP, htmlspecialchars translates stuff like <htmltag/> into &lt;htmltag/&gt;

我知道 escape()encodeURI() 不能这样工作.

I know that escape() and encodeURI() do not work this way.

推荐答案

您的解决方案代码有问题——它只会转义每个特殊字符的第一次出现.例如:

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

escapeHtml('Kip\'s <b>evil</b> "test" code\'s here');
Actual:   Kip&#039;s &lt;b&gt;evil</b> &quot;test" code's here
Expected: Kip&#039;s &lt;b&gt;evil&lt;/b&gt; &quot;test&quot; code&#039;s here

这是正常工作的代码:

function escapeHtml(text) {
  return text
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
}


更新

以下代码将产生与上述相同的结果,但性能更好,尤其是在大文本块上(感谢 jbo5112).

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

这篇关于JavaScript 中的 HtmlSpecialChars 等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆