当前位置:  开发笔记 > 编程语言 > 正文

在Javascript中将特殊字符转换为HTML

如何解决《在Javascript中将特殊字符转换为HTML》经验,为你挑选了9个好方法。

是否有任何人知道如何特殊字符转换为HTMLJavascript

例:

&(&符号)变成了&.

"(双引号)成为"ENT_NOQUOTES未设置.

'(单引号)'仅在ENT_QUOTES设置时才变为.

<(小于)成为<.

>(大于)成为>.

Cerebrus.. 204

在我看来,最好的方法是使用浏览器的内置HTML转义功能来处理许多情况.要做到这一点,只需在DOM树中创建一个元素,并将元素设置innerText为您的字符串.然后检索innerHTML元素.浏览器将返回HTML编码的字符串.

function HtmlEncode(s)
{
  var el = document.createElement("div");
  el.innerText = el.textContent = s;
  s = el.innerHTML;
  return s;
}

测试运行:

alert(HtmlEncode('&;\'><"'));

输出:

&;'><"

这种转义HTML的方法也被Prototype JS库使用,但与我给出的简单示例不同.

注意:您仍然需要自己转义引号(双引号和单引号).您可以在此处使用其他人概述的任何方法.



1> Cerebrus..:

在我看来,最好的方法是使用浏览器的内置HTML转义功能来处理许多情况.要做到这一点,只需在DOM树中创建一个元素,并将元素设置innerText为您的字符串.然后检索innerHTML元素.浏览器将返回HTML编码的字符串.

function HtmlEncode(s)
{
  var el = document.createElement("div");
  el.innerText = el.textContent = s;
  s = el.innerHTML;
  return s;
}

测试运行:

alert(HtmlEncode('&;\'><"'));

输出:

&;'><"

这种转义HTML的方法也被Prototype JS库使用,但与我给出的简单示例不同.

注意:您仍然需要自己转义引号(双引号和单引号).您可以在此处使用其他人概述的任何方法.


使用jQuery,`output = $('
').text(input).html()`
两种方法都不会将'转换为' 和"进入"所以它仍然可以用于XSS攻击.
注意`删除el`在这里是个错误.http://perfectionkills.com/understanding-delete/

2> Steven..:

你需要一个像这样的功能

return mystring.replace(/&/g, "&").replace(/>/g, ">").replace(/

但考虑到您对单/双引号的不同处理的愿望.


正则表达式中的@JohnnyBizzle`/g`表示"全局".简单地说,所有出现的字符串都将被替换.没有`/ g`只会替换第一个匹配.

3> KooiInc..:

此通用函数将每个非字母字符编码为其htmlcode(数字):

function HTMLEncode(str) {
    var i = str.length,
        aRet = [];

    while (i--) {
        var iC = str[i].charCodeAt();
        if (iC < 65 || iC > 127 || (iC>90 && iC<97)) {
            aRet[i] = '&#'+iC+';';
        } else {
            aRet[i] = str[i];
        }
    }
    return aRet.join('');
}



4> Matt Hanson..:

创建一个使用字符串的函数 replace

function convert(str)
{
  str = str.replace(/&/g, "&");
  str = str.replace(/>/g, ">");
  str = str.replace(/



5> 小智..:

来自Mozilla ......

请注意,charCodeAt将始终返回小于65,536的值.这是因为较高的代码点由一对(较低值)"代理"伪字符表示,这些伪字符用于构成真实字符.因此,为了检查或重现值为65,536及以上的单个字符的完整字符,对于这些字符,不仅需要检索charCodeAt(i),还需要检索charCodeAt(i + 1)(就像检查一样) /再现一个带有两个>字母的字符串).

最佳解决方案

/**
 * (c) 2012 Steven Levithan 
 * MIT license
 */
if (!String.prototype.codePointAt) {
    String.prototype.codePointAt = function (pos) {
        pos = isNaN(pos) ? 0 : pos;
        var str = String(this),
            code = str.charCodeAt(pos),
            next = str.charCodeAt(pos + 1);
        // If a surrogate pair
        if (0xD800 <= code && code <= 0xDBFF && 0xDC00 <= next && next <= 0xDFFF) {
            return ((code - 0xD800) * 0x400) + (next - 0xDC00) + 0x10000;
        }
        return code;
    };
}

/**
 * Encodes special html characters
 * @param string
 * @return {*}
 */
function html_encode(string) {
    var ret_val = '';
    for (var i = 0; i < string.length; i++) { 
        if (string.codePointAt(i) > 127) {
            ret_val += '&#' + string.codePointAt(i) + ';';
        } else {
            ret_val += string.charAt(i);
        }
    }
    return ret_val;
}

用法示例:

html_encode("?");



6> 小智..:
function char_convert() {

    var chars = ["©","Û","®","ž","Ü","Ÿ","Ý","$","Þ","%","¡","ß","¢","à","£","á","À","¤","â","Á","¥","ã","Â","¦","ä","Ã","§","å","Ä","¨","æ","Å","©","ç","Æ","ª","è","Ç","«","é","È","¬","ê","É","­","ë","Ê","®","ì","Ë","¯","í","Ì","°","î","Í","±","ï","Î","²","ð","Ï","³","ñ","Ð","´","ò","Ñ","µ","ó","Õ","¶","ô","Ö","·","õ","Ø","¸","ö","Ù","¹","÷","Ú","º","ø","Û","»","ù","Ü","@","¼","ú","Ý","½","û","Þ","€","¾","ü","ß","¿","ý","à","‚","À","þ","á","ƒ","Á","ÿ","å","„","Â","æ","…","Ã","ç","†","Ä","è","‡","Å","é","ˆ","Æ","ê","‰","Ç","ë","Š","È","ì","‹","É","í","Œ","Ê","î","Ë","ï","Ž","Ì","ð","Í","ñ","Î","ò","‘","Ï","ó","’","Ð","ô","“","Ñ","õ","”","Ò","ö","•","Ó","ø","–","Ô","ù","—","Õ","ú","˜","Ö","û","™","×","ý","š","Ø","þ","›","Ù","ÿ","œ","Ú"]; 
    var codes = ["©","Û","®","ž","Ü","Ÿ","Ý","$","Þ","%","¡","ß","¢","à","£","á","À","¤","â","Á","¥","ã","Â","¦","ä","Ã","§","å","Ä","¨","æ","Å","©","ç","Æ","ª","è","Ç","«","é","È","¬","ê","É","­","ë","Ê","®","ì","Ë","¯","í","Ì","°","î","Í","±","ï","Î","²","ð","Ï","³","ñ","Ð","´","ò","Ñ","µ","ó","Õ","¶","ô","Ö","·","õ","Ø","¸","ö","Ù","¹","÷","Ú","º","ø","Û","»","ù","Ü","@","¼","ú","Ý","½","û","Þ","€","¾","ü","ß","¿","ý","à","‚","À","þ","á","ƒ","Á","ÿ","å","„","Â","æ","…","Ã","ç","†","Ä","è","‡","Å","é","ˆ","Æ","ê","‰","Ç","ë","Š","È","ì","‹","É","í","Œ","Ê","î","Ë","ï","Ž","Ì","ð","Í","ñ","Î","ò","‘","Ï","ó","’","Ð","ô","“","Ñ","õ","”","Ò","ö","•","Ó","ø","–","Ô","ù","—","Õ","ú","˜","Ö","û","™","×","ý","š","Ø","þ","›","Ù","ÿ","œ","Ú"];

    for(x=0; x



7> 小智..:
function ConvChar( str ) {
  c = {'<':'<', '>':'>', '&':'&', '"':'"', "'":''',
       '#':'#' };
  return str.replace( /[<&>'"#]/g, function(s) { return c[s]; } );
}

alert( ConvChar('<-"-&-"->-<-\'-#-\'->') );

结果:

<-"-&amp;-"->-<-'-#-'->

在testarea标签:

<-"-&-"->-<-'-#-'->

如果你只是改变长代码中的一个小字符......



8> Christos Lyt..:

对于那些想要像字符串内部那样解码整数字符代码的人&#xxx;,请使用以下函数:

function decodeHtmlCharCodes(str) { 
  return str.replace(/(&#(\d+);)/g, function(match, capture, charCode) {
    return String.fromCharCode(charCode);
  });
}

// Will output "The show that gained int’l reputation’!"
console.log(decodeHtmlCharCodes('The show that gained int’l reputation’!'));


9> Serj Sagan..:

正如dragon最干净的方法提到的是jQuery

function HtmlEncode(s) {
    return $('
').text(s).html(); } function HtmlDecode(s) { return $('
').html(s).text(); }

推荐阅读
Life一切安好
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有