我需要解码html实体,例如:&<>"`'

按照此SO post中的建议,我试图将underscore.js中的_.unescape()用于此任务。

但是,unescape()似乎没有任何作用。当我称它为在以下字符串上,它仅返回字符串本身:

const line = 'Tweag I/O | Paris, France &amp Berlin, Germany | Full-time. Give us a shout at [email protected]!'


要进行验证,可以转到JSBin并粘贴以下代码:

const line = 'Tweag I/O | Paris, France &amp Berlin, Germany | Full-time. Give us a shout at [email protected]!'
console.log(line)

const decodedLine = unescape(line)
console.log(decodedLine)


不要忘记通过单击underscore.js按钮时出现的下拉列表中的Add library库来添加它。

更新资料

如@DanPrince的答案中所述,unescape()仅解码一组有限的字符:

&<>"`'

但是,将我的行从上面的示例更改为以下示例仍然无效;(即使这次我使用'&):

const line = `'Tweag I'O | Paris, France & Berlin, Germany | Full-time. Give us a shout at [email protected]!'`


最终更新

我通过使用其他库解决了我的问题。我现在使用的是he而不是underscore.js,它完全提供了我正在寻找的功能。

现在,我可以调用decode(line),所有html实体都将正确翻译。但是,我将跟踪该问题的答案,并接受可以解释为什么unescape()无法按预期工作的答案。

最佳答案

the source中查找下划线,所有内容都会通过以下地图进行翻译。

var escapeMap = {
  '&': '&',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#x27;',
  '`': '&#x60;'
};
var unescapeMap = _.invert(escapeMap);


字符串中的两个转义的实体是&#x2F;&amp,它们都不出现在转义图中。您可以通过添加分号来修复&amp;

虽然它不是特别有效,但是您可以使用answer suggested here

另外,当我在jsbin中使用_.unescape时,我得到了预期的行为,而我认为您的代码使用了本机的unescape函数。

10-06 08:04