[英]How can I convert strings with HTML entities into normalized form?
I want to use jquery to convert text containing strings like 我想使用jquery来转换包含 之类的字符串的文本 
, etc into a more human-readable form. 
等格式转换成更易于理解的形式。 This works in jsfiddle: 这在jsfiddle中有效:
<input id="stupid-approach" type="hidden">
function js_text(theVal) {
$("#stupid-approach").html(theVal);
x = $("#stupid-approach").html();
return x;
}
alert(js_text("é"));
But I'm wondering if there is a way to do it that does not rely on a hidden field in the DOM? 但是我想知道是否有一种方法可以不依赖DOM中的隐藏字段?
in consideration of the feedback about jQuery's .html() method's evaluation of script tags, here is a safer native version that's not tooo unwieldy: 考虑到有关jQuery的.html()方法对脚本标签进行评估的反馈,这是一个更安全的本地版本,不会太笨拙:
function js_text(theVal) {
var div=document.createElement("div");
div.innerHTML=theVal;
return div.textContent;
}
use it instead of $(xxx).html() when you don't trust the input 100% 当您不信任输入100%时,请使用它代替$(xxx).html()
No. There's no purely programmatic way to do this that doesn't involve getting the browser to treat the string as HTML, as in your example. 号有没有做到这一点,并不涉及让浏览器处理字符串作为HTML,在你的榜样纯粹的编程方式。 (Beware untrusted inputs when doing that, by the way - it's an injection attack waiting to happen.) (顺便提一下,在执行此操作时请注意不受信任的输入,这是等待发生的注入攻击。)
您应该能够做到:
return $('<div>'+ theVal + '</div>').html();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.