HtmlSpecialChars等效于Javascript? [英] HtmlSpecialChars equivalent in Javascript?

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

问题描述

显然,这比我以为会更难找到。它甚至是如此简单...



有没有相当于PHP内置的Javascript的htmlspecialchars的功能?我知道这是很容易实现的,但是使用内置函数(如果有的话)只是更好。



对于那些不熟悉PHP的人来说,htmlspecialchars会翻译像< htmltag /> & lt; htmltag /& gt;



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

解决方案

解决方案代码有问题 - 它只会逃避每个特殊字符的首次出现。例如:

  escapeHtml('Kip\'s< b> evil< / b>testcode \\在这里) 
实际:Kip&#039; s& lt; b& gt; evil< / b> &test代码在这里
预期:Kip&#039; s& lt; b& gt; evil& lt; / b& quot; test& quot; code&#039;在这里

这里是正常工作的代码:

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






更新



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

  function escapeHtml(text){
var map =
'&':'& amp;',
'<':'& lt;',
'>':'& $ b'':'& quot;',
':'&#039;'
};

return text.replace(/ ;”'] / g,function(m){return map [m];});
}


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 Javascript? I know it's fairly easy to implement that yourself, but using a built-in function, if available, is just nicer.

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

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

Here is code that works properly:

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


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 = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };

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

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

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