简体   繁体   English

在 JavaScript 中解码 HTML 实体?

[英]Decode HTML entities in JavaScript?

Sample conversions:示例转换:

 & -> `&`
 >  -> `>`

Any small library function that can handle this?任何可以处理这个的小型库函数?

I have on my utility belt this tiny function always:我的实用腰带上总是有这个小功能:

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes[0].nodeValue;
}

htmlDecode("&"); // "&"
htmlDecode(">"); // ">"

It will work for all HTML Entities .它适用于所有HTML 实体

Edit: Since you aren't in a DOM environment, I think you will have to do it by the "hard" way:编辑:由于您不在 DOM 环境中,我认为您必须通过“困难”的方式来做到这一点:

function htmlDecode (input) {
  return input.replace(/&/g, "&")
              .replace(/&lt;/g, "<")
              .replace(/&gt;/g, ">");
              //...
}

If you don't like the chained replacements, you could build an object to store your entities, eg:如果您不喜欢链式替换,您可以构建一个对象来存储您的实体,例如:

function htmlDecode (input) {
  var entities= {
    "&amp;": "&",
    "&lt;": "<",
    "&gt;": ">"
    //....
  };

  for (var prop in entities) {
    if (entities.hasOwnProperty(prop)) {
      input = input.replace(new RegExp(prop, "g"), entities[prop]);
    }
  }
  return input;
}

Looks like this will do:看起来像这样:

function html_entity_decode(s) {
  var t=document.createElement('textarea');
  t.innerHTML = s;
  var v = t.value;
  t.parentNode.removeChild(t);
  return v;
}

Source 来源

A robust HTML entity encoder/decoder written in JavaScript.用 JavaScript 编写的强大的 HTML 实体编码器/解码器。

https://mths.be/he https://mths.be/he

he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. he (代表“HTML 实体”)是一个用 JavaScript 编写的强大的 HTML 实体编码器/解码器。 It supports all standardized named character references as per HTML , handles ambiguous ampersands and other edge cases just like a browser would , has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine.它支持所有标准化的 HTML 命名字符引用像浏览器一样处理不明确的&符号和其他边缘情况,具有广泛的测试套件,并且——与许多其他 JavaScript 解决方案相反——可以很好地处理星体 Unicode 符号。 An online demo is available.提供在线演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM