javascript - 两个相同字符串值的实例不相等
将数字格式化为货币样式的字符串时,返回的值与预期不符。
const expected = `12,09 €`;
const formatted =
new Intl.NumberFormat(`de-De`, { style: `currency`, currency: `EUR` }).format(12.09);
expect(formatted).toEqual(expected); // Fail
expected === formatted; // false
// Logged values
console.log(`FORMATTED: type = ${typeof formatted}, value = '${actual}';`);
console.log(`EXPECTED: type = ${typeof expected}, value = '${expected}';`);
// FORMATTED: type = string, value = '12,09 €';
// EXPECTED: type = string, value = '12,09 €';
但是
new Intl.NumberFormat(`de-De`, { style: `currency`, currency: `EUR` }).format(12.09);
// returns "12,09 €"
`12,09 €` === `12,09 €`; // true
typeof formatted; // "string"
问题:为什么两个相似的字符串不相等?
答案#1
Intl.NumberFormat 返回的字符串包含不间断空格(字符代码160),而你的 expected 字符串使用的是普通空格(字符代码32)。
expected[5] === formatted[5]/假
看看这个讨论串:https://github.com/nodejs/node/issues/24674
我认为你可以简单地用 replace 函数来解决这个问题。例如:
const expected = `12,09 €`.replace(/\s/, String.fromCharCode(160));
const formatted =
new Intl.NumberFormat(`de-De`, {
style: `currency`,
currency: `EUR`
}).format(12.09);
console.log(expected === formatted);(提示:把它提取到一个单独的函数中,并让该函数接收一个字符串并规范化空格,会是一个好主意)
答案#2
formatted 中的空格字符是 0xC2A0,而 expected 中的是 0x20
