在javascript中翻转&符号 [英] Unescaping ampersand characters in javascript
问题描述
我正在正确显示包含转义字符的值(即撇号存储为 \'
而不是'
和括号是& gt;
和& lt;
而不是> ;
和<
)。
存储在我的数据库中的项目的字符('<>
)转义为( \'& lt;& gt;
)。当我尝试通过JavaScript动态地将它们添加到页面时,它们以Firefox的转义形式打印出来,而不是返回到正常的值,如IE(& lt;
正在打印到HTML,而不仅仅是
。
< HTML>
< head>
< script type =text / javascript>
$(document).ready(function(){
var str =& gt;
$(document.body).html(str);
} );
< / script>
< / head>
< body>
< / body>
< / html>
我知道如果我只是做一个替换,我可以打印正确,但这样做,我允许注册HTML代码,这就是为什么我首先逃脱了字符串。
添加:
首先,我对我最初的帖子中的错误表示歉意。仔细检查后,在我使用$()。html()的情况下,字符串正确打印。不正确打印的时间是当我使用下面的代码时。
var str =& ;
$('#inputField')。val(str);
在这种情况下,文本>被显示,而不是>。有可以解决这个问题吗?
你需要像这样解码:
$('#myText')。val($(< div />)。html(str).text());
演示: http://jsfiddle.net/QUbmK/
您可以将解码部分移动到函数,然后调用它:
function jDecode(str){
return $(< div />)。html(str) );
}
$('#myText')。val(jDecode(str));
I'm having trouble properly displaying values that contain escaped characters (i.e. apostrophes are stored as \'
and not '
and brackets are >
and <
rather than >
and <
).
Items stored in my database have the characters (' < >
) escaped to (\' < >
), respectively. When I try to dynamically add them to the page with JavaScript, they print out in the escaped form in Firefox, rather than returning to their normal values like in IE (<
is being printed to the HTML rather just <
).
<html>
<head>
<script type="text/javascript">
$(document).ready(function() {
var str = ">";
$(document.body).html(str);
});
</script>
</head>
<body>
</body>
</html>
I know that if I simply do a replace, I can print correctly, but by doing so, I'm allowing the injection of HTML code, which is why I escaped the string in the first place.
ADDED:
Firstly, I apologize about the mistakes in my initial post. After closer examination, in the instances where I am using $().html(), the strings are printing correctly. The times where they aren't printing correctly are when I am using code like below.
var str = ">";
$('#inputField').val(str);
In this instance, the text ">" is shown, rather than ">". Is there something I can do to fix this?
You need to decode them like this:
$('#myText').val($("<div/>").html(str).text());
Demo: http://jsfiddle.net/QUbmK/
You can move the decode part to function too and call that instead:
function jDecode(str) {
return $("<div/>").html(str).text();
}
$('#myText').val(jDecode(str));
这篇关于在javascript中翻转&符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!