字符串反转义的问题,困扰了我一天了!
本帖最后由 webstandards 于 2014-01-10 00:27:44 编辑 从数据库里读出来的字符串是已经被转义过了的,要在浏览器显示时再把它反转义。
没进行反转义是下面这个效果。
<div class="itemContent" id="itemContenter">
<p>
8864的萨芬的萨芬55
</p>
</div>
我用了上面的反转义函数过了一遍,失败。
<script type="text/javascript">
var itemContent="<p>8864的萨芬的萨芬55</p>
<p>8864的萨芬的萨芬55</p>"
itemContent=itemContent.replace(/>/g,">").replace(/</g,"<");
itemContenter.innerHTML=itemContent;
</script>
后来发现只要被反转义的字符串里有换行,就没法反转义。如果被反转义的字符串去掉换行,即变成
<p>8864的萨芬的萨芬55</p>
就可以成功反转义。
但是从数据库里读出来的字符串都是带有换行的,用什么方法可以实现反转义啊?
[解决办法]
什么编程语言?
php 用htmlspecialchars_decode($str);
JS代码参考:http://phpjs.org/functions/htmlspecialchars_decode/
function htmlspecialchars_decode (string, quote_style) {
var optTemp = 0,
i = 0,
noquotes = false;
if (typeof quote_style === 'undefined') {
quote_style = 2;
}
string = string.toString().replace(/</g, '<').replace(/>/g, '>');
var OPTS = {
'ENT_NOQUOTES': 0,
'ENT_HTML_QUOTE_SINGLE': 1,
'ENT_HTML_QUOTE_DOUBLE': 2,
'ENT_COMPAT': 2,
'ENT_QUOTES': 3,
'ENT_IGNORE': 4
};
if (quote_style === 0) {
noquotes = true;
}
if (typeof quote_style !== 'number') {
quote_style = [].concat(quote_style);
for (i = 0; i < quote_style.length; i++) {
if (OPTS[quote_style[i]] === 0) {
noquotes = true;
} else if (OPTS[quote_style[i]]) {
optTemp = optTemp
[解决办法]
OPTS[quote_style[i]];
}
}
quote_style = optTemp;
}
if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
string = string.replace(/�*39;/g, "'");
}
if (!noquotes) {
string = string.replace(/"/g, '"');
}
string = string.replace(/&/g, '&');
return string;
}
[解决办法]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">
window.onload=function(){
var itemContent="<p>8864的萨芬的萨芬55</p>"+
"<p>8864的萨芬的萨芬55</p>"
var k=document.createTextNode(itemContent);
itemContenter.appendChild(k);
}
</script>
</head>
<body>
<div id="itemContenter"></div>
</body>
</html>
建个textNode试试
[解决办法]
<div class="itemContent" id="itemContenter">
<p>
8864的萨芬的萨芬55
</p>
</div>
<script>
function decodehtml(s) {
return s.replace(/>/gi, '>').replace(/</gi, '<');
}
var d = document.getElementById('itemContenter');
d.innerHTML = decodehtml(d.innerHTML);
</script>
[解决办法]
从数据库里读出来的字符串是已经被转义过了的,要在浏览器显示时再把它反转义。
没进行反转义是下面这个效果。
<div class="itemContent" id="itemContenter">
<p>
8864的萨芬的萨芬55
</p>
</div>
我用了上面的反转义函数过了一遍,失败。
<script type="text/javascript">
var itemContent="<p>8864的萨芬的萨芬55</p>
<p>8864的萨芬的萨芬55</p>"
itemContent=itemContent.replace(/>/g,">").replace(/</g,"<");
itemContenter.innerHTML=itemContent;
</script>
---------->函数写成这样就没问题了。
<script type="text/javascript">
itemContenter.innerText = strFromDB <----从数据库得到的原始数据
itemContenter.innerHTML=itemContenter.innerText;
</script>
[解决办法]
如果可以,最好是源找起,把存入料的候或料取出的候,就把行改成<br>