简体   繁体   English

如何将带有HTML实体的字符串转换为规范化形式?

[英]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("&eacute;"));

But I'm wondering if there is a way to do it that does not rely on a hidden field in the DOM? 但是我想知道是否有一种方法可以不依赖DOM中的隐藏字段?

just create an empty element, there's no need to have an actual hidden element in the DOM : 只需创建一个空元素,就无需在DOM中有一个实际的隐藏元素:

function js_text(theVal) {
    return $("<div />", {html: theVal}).text();
}

FIDDLE 小提琴

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.

相关问题 如何在我的 twitter 机器人中转换 html 实体? - How can i convert html entities in my twitter bot? CKEDITOR:如何转换所有html实体 - CKEDITOR: how to I convert ALL html entities 如何在保留 HTML 标签(Javascript/NodeJS)的同时清理字符并将其转换为 HTML 实体? - How can I sanitize and convert characters to HTML entities while preserving HTML tags (Javascript/NodeJS)? 如何将图像(从 HTML 表单)转换为图标? - How can I convert an image (from an HTML form) to a favicon? 如何转换不显示 HTML 4 个实体? - How to convert not HTML 4 entities to be shown? 如何在我的模板(Angular2 / TypeScript)中将HTML字符串转换为HTML? - How can I convert strings of HTML into HTML in my template (Angular2/TypeScript)? 如何将html字符串转换为dataURI - How to convert html strings into dataURI 如何创建用于生成 hsl 颜色数组的标准化分布? - How can I create a normalized distribution for producing an hsl color array? 如何从规范化的树列表中构建树 - How can I build a tree from a normalized tree list 如何使用javascript将html中的表单字段转换为UTF8? - How can I convert a form field in html to UTF8 using javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM