首页 > 解决方案 > 带有 html 实体的解码字符串不等于字符串文字

问题描述

我试图实现这个线程中提出的解决方案来解码带有 html 实体的字符串,例如“foo bar”到“foo bar”。

从视觉上看,它似乎有效。但是我的快速 Jest 测试失败了:

Expected: "foobar"
Received: "foobar"

  3 | describe('encryption/decodeHtml', () => {
  4 |   it.each([['foo bar', 'foo bar'], ['foo­bar', 'foobar'], ['foo&bar', 'foo&bar']])('should decode html entities', (val, expected) => {
> 5 |     expect(decodeHtml(val)).toEqual(expected);
    |                             ^
  6 |   })
  7 | });
  8 |

一快Object.is(decodeHtml(' '), ' ')也产生false

有什么我不熟悉的 JS-Strings 吗?

标签: javascripthtmljestjsescaping

解决方案


正如Andreas在评论中指出的那样,我忘记了字符串的字节表示。

看这个例子:

toBytes('foo bar') -> Uint8Array(7) [102, 111, 111, 32, 98, 97, 114]
toBytes(decodeHtml('foo bar')) -> Uint8Array(8) [102, 111, 111, 194, 160, 98, 97, 114]

事后看来,这很明显,因为中断空间和非中断空间(当然)是不同的字符。


推荐阅读