如何使用javascript转换特殊字符及其实体名称(如& with&)

时间:2015-02-17 05:35:11

标签: javascript jquery

我的要求很少,有JSON个数据,我想将所有specialChars转换为escapeChars, 我尝试使用以下代码,但它会引发Object doesn't support property or method 'split'之类的错误,请将您的想法分享给我。

function applyEscapeChars()
                {                              
                            var str = { "aaData": ["dummy < data","ampersand&aaa","2015-02-16","2015-02-16",470.5,"xyz",1,0,"","Error: 1 Invalid format/sample","---"]}                            
                            var specialChars = new Array();
                                specialChars[0] = "&";
                                specialChars[1] = "\"";
                                specialChars[2] = "'";
                                specialChars[3] = "<";
                                specialChars[4] = ">";
                                var escapeChars = new Array();
                                escapeChars[0] = "&amp;";
                                escapeChars[1] = "&quot;";
                                escapeChars[2] = "&apos;";
                                escapeChars[3] = "&lt;";
                                escapeChars[4] = "&gt;";

                                for (var i =0; i < specialChars.length; i++ )
                                {                             
                                         str = JSON.stringify(str ).split(specialChars[i]).join(escapeChars[i]);                                             
                                }
                                //alert(str);

                                return str;

                }

现在一切正常,除了less than symbol(<)

1 个答案:

答案 0 :(得分:0)

您可以让浏览器执行html编码吗?

function htmlEncode(value){
  //create a in-memory div, set it's inner text(which jQuery automatically encodes)
  //then grab the encoded contents back out.  The div never exists on the page.
  return $('<div/>').text(value).html();
}

取自HTML-encoding lost when attribute read from input field