来自underscore.js的unescape()函数不起作用

时间:2016-04-01 09:03:13

标签: javascript underscore.js decoding

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

根据此SO post的建议,我尝试使用underscore.js中的_.unescape()来执行此任务。

但是,unescape()似乎没有任何效果。我打电话的时候,例如在下面的字符串中,它只返回字符串本身:

const line = 'Tweag I/O | Paris, France &amp Berlin, Germany | Full-time. Give us a shout at jobs@tweag.io!'

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

const line = 'Tweag I/O | Paris, France &amp Berlin, Germany | Full-time. Give us a shout at jobs@tweag.io!'
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 jobs@tweag.io!'` 

最终更新

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

现在,我可以调用decode(line)所有 html实体进行正确翻译。我会跟进这个问题的答案,然后接受解释为什么unescape()无法正常工作的答案。

1 个答案:

答案 0 :(得分:1)

查看the source下划线,一切都通过以下地图进行翻译。

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

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

虽然效率不高,但您可以使用answer suggested here

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