[英]How to Convert special chars with their entity names (like & with &) using javascript
I have small requirement, have JSON
data and I would like to convert all specialChars
with escapeChars
, I tried with following code but it throws an error like Object doesn't support property or method 'split'
, please share me your ideas. 我的要求不高,有
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] = "&";
escapeChars[1] = """;
escapeChars[2] = "'";
escapeChars[3] = "<";
escapeChars[4] = ">";
for (var i =0; i < specialChars.length; i++ )
{
str = JSON.stringify(str ).split(specialChars[i]).join(escapeChars[i]);
}
//alert(str);
return str;
}
Now everything is working fine except less than symbol(<)
现在一切正常,但
less than symbol(<)
Is it ok for you to let the browser do the html encoding? 您可以让浏览器进行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();
}
It's taken from HTML-encoding lost when attribute read from input field 从输入字段读取属性时丢失的HTML编码中获取
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.