Safari 和 Chrome 之间的不同 ascii 值

Different ascii value between Safari and Chrome

使用 macOS 和 BigSur 版本 11.4。

我 mac 上的一个文件名为:второй

如果我将文件名复制并粘贴到 chrome 控制台并打印 "второй".charCodeAt(5) - 1080

是 Safari:"второй".charCodeAt(5) - 1081

这会导致我的应用程序出现一些差异。

有没有办法处理这个问题,使两种浏览器的行为相同?

有(至少)两种方式在 Unicode 中编写该单词:второй(如您的问题),它使用 и (U+0438) followed by the combining character for the mark (U+0306); and второй, which uses a single code point (U+0439)这些的组合(й)。使用单独字母和组合标记的是规范化形式 D(“规范分解”,其中尽可能使用带有组合标记的单独代码点),使用组合代码点的是规范化形式 C(“规范分解”组合”,其中尽可能使用组合代码点。

因此,无论出于何种原因,在 Safari 上,您的字符串(在表单 D 中)正在规范化为表单 C,但在 Chrome 上不是。

为确保您处理的是相同的代码点序列,您可以使用 normalize 方法 (ES2015+) 规范化字符串。它默认为 NFC,但如果你想要 NFD,你可以传递它 "NFD":

const original = "второй";
console.log("original:", original.length, original.charCodeAt(5));
const nfc = original.normalize(); // Defaults to "NFC"
console.log("NFC:", nfc.length, nfc.charCodeAt(5));
const nfd = nfc.normalize("NFD");
console.log("NFD:", nfd.length, nfd.charCodeAt(5));

请注意,charCodeAt 在 UTF-16 代码 units 中工作,而不是代码 pointspost on my blog about the difference), although it happens that in your example all of the code points are represented by a single code unit. You can use codePointAt to而是查看代码点,尽管(再次)在这种特殊情况下它没有什么不同。