在JavaScript中解码HTML实体? [英] Decode HTML entities in JavaScript?

查看:112
本文介绍了在JavaScript中解码HTML实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

转换示例:

 & amp; amp; amp; amp; - > `&`
& gt; - > `>`

任何小型库函数都可以处理这个问题吗?

 <$ c $ 

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

htmlDecode(& amp;); //&
htmlDecode(& gt;); //>

它适用于所有 HTML Entities



编辑:既然你不是'在一个DOM环境中,我认为你必须用硬的方式来完成它:

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

如果您不喜欢你可以建立一个对象来存储你的实体,例如:

实体= {
& amp;:&,
& lt;:<,
& gt;:>
// ....
};

for(var prop in entities){
if(entities.hasOwnProperty(prop)){
input = input.replace(new RegExp(prop,g),实体[丙]);
}
}
返回输入;
}


Sample conversions:

 &amp; -> `&`
 &gt;  -> `>`

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("&amp;"); // "&"
htmlDecode("&gt;"); // ">"

It will work for all HTML Entities.

Edit: Since you aren't in a DOM environment, I think you will have to do it by the "hard" way:

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

If you don't like the chained replacements, you could build an object to store your entities, e.g.:

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;
}

这篇关于在JavaScript中解码HTML实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆