Dan*_*Tao 184 javascript jquery html-entities
假设我从服务请求中获得了一些JSON,如下所示:
{
"message": "We're unable to complete your request at this time."
}
Run Code Online (Sandbox Code Playgroud)
我不确定为什么那个抄袭被编码为那个('); 我所知道的是我想解码它.
这是一种使用jQuery的方法,它突然出现在我脑海中:
function decodeHtml(html) {
return $('<div>').html(html).text();
}
Run Code Online (Sandbox Code Playgroud)
但这似乎(非常)hacky.什么是更好的方式?有"正确"的方式吗?
Rob*_*b W 360
这是我最喜欢的HTML字符解码方式.使用此代码的优点是标记也被保留.
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
Run Code Online (Sandbox Code Playgroud)
输入:
Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
Run Code Online (Sandbox Code Playgroud)
输出:
Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
Run Code Online (Sandbox Code Playgroud)
Mat*_*ens 94
不要使用DOM来执行此操作.使用DOM解码HTML实体(如当前接受的答案中所建议的)会导致跨浏览器结果的差异.
对于根据HTML标准的算法解码字符引用一个强大的和确定性的解决方案,使用了他的库.从其自述文件:
他(对于"HTML实体")是一个用JavaScript编写的健壮的HTML实体编码器/解码器.它支持所有标准化的命名字符引用,根据HTML,处理模糊的&符号和其他边缘情况,就像浏览器一样,具有广泛的测试套件,并且 - 与许多其他JavaScript解决方案相反 - 他处理星体Unicode符号就好了.提供在线演示.
这是你如何使用它:
he.decode("We're unable to complete your request at this time.");
? "We're unable to complete your request at this time."
Run Code Online (Sandbox Code Playgroud)
免责声明:我是他图书馆的作者.
有关更多信息,请参阅此Stack Overflow答案.
Alx*_*ndr 30
如果你不想使用html/dom,你可以使用正则表达式.我没有测试过这个; 但有些东西:
function parseHtmlEntities(str) {
return str.replace(/&#([0-9]{1,3});/gi, function(match, numStr) {
var num = parseInt(numStr, 10); // read num as normal number
return String.fromCharCode(num);
});
}
Run Code Online (Sandbox Code Playgroud)
注意:这只适用于数字html实体,而不适用于&oring;等.
修复了函数(一些拼写错误),在这里测试:http://jsfiddle.net/Be2Bd/1/
Jas*_*ams 25
jQuery将为您编码和解码.
function htmlDecode(value) {
return $("<textarea/>").html(value).text();
}
function htmlEncode(value) {
return $('<textarea/>').text(value).html();
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#encoded")
.text(htmlEncode("<img src onerror='alert(0)'>"));
$("#decoded")
.text(htmlDecode("<img src onerror='alert(0)'>"));
});
</script>
<span>htmlEncode() result:</span><br/>
<div id="encoded"></div>
<br/>
<span>htmlDecode() result:</span><br/>
<div id="decoded"></div>Run Code Online (Sandbox Code Playgroud)
hyp*_*ers 20
有一个JS函数来处理xxx样式的实体:
GitHub上的函数
// encode(decode) html text into html entity
var decodeHtmlEntity = function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
var encodeHtmlEntity = function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
};
var entity = '高级程序设计';
var str = '??????';
console.log(decodeHtmlEntity(entity) === str);
console.log(encodeHtmlEntity(str) === entity);
// output:
// true
// true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
196460 次 |
| 最近记录: |