【问题标题】:How do I reverse `String.fromCodePoint`, i.e. convert a string to an array of code points?如何反转“String.fromCodePoint”,即将字符串转换为代码点数组?
【发布时间】:2021-05-21 07:42:41
【问题描述】:

String.fromCodePoint(...[127482, 127480]) 给了我一面美国国旗(????????)。

如何将标志转回[127482, 127480]

【问题讨论】:

  • Array.from("????????", (codeUnit) => codeUnit.codePointAt())?这基本上是逆运算……
  • @T.J.Crowder 方法名称codePointAt 总是让我感到困惑……是数字或“字符”(即字符串;还是字形(簇)或字形?)的代码点? codePoint.codePointAt() 听起来我想获取代码点的代码点,这并没有什么意义……还是应该是(string) => string.codePointAt()
  • @SebastianSimon - 你并不孤单。 :-) 是的,我会选择最后一个(事实上,当我将您的方法添加到下面的答案中时,我就是这样做的:-D)。代码点是唯一标识 Unicode 标准中的“字符”的数字(“字符”在那里非常松散)。代码 unit 是一个数字,可能需要与另一个数字组合以识别字符,具体取决于所使用的 transformation format。这个问题中的标志是一个特别复杂的例子,因为它是一个两个代码点的东西,用于标识一个......
  • ...emoji,所以我喜欢用眨眼的脸 (????) 作为示例:它是 Unicode 数据库中的代码点 0x1F609,字符 U+1F609。 JavaScript 字符串实际上是 UTF-16(但可以容忍损坏的代理对),这是 Unicode 的 16 位 转换格式,其中每个值都适合 16 位。由于 Unicode 是 21 位格式,这意味着某些“字符”必须使用两个 16 位单元——代码 units。在眨眼的情况下,它们是 0xD83D 和 0xDE09 - 代理对,在 UTF-16 中,它们结合起来给我们...
  • ...眨眼(????)。在 UTF-8 中,可能需要 1 到 4 个代码单元来构成一个代码点(对于眨眼的脸,它是 0xF0 0x9F 0x98 0x89)。我有一篇关于 here 的简短博客文章,我也在我最近一本书的第 10 章(我的个人资料中的链接)中详细介绍了它。 (抱歉评论太长了!)

标签: javascript string unicode-string codepoint


【解决方案1】:

您正在寻找codePointAt,可能使用spread(等)转换回数组,然后映射它们中的每一个。

console.log(theString.codePointAt(0)); // 127482
console.log(theString.codePointAt(2)); // 127480
// Note −−−−−−−−−−−−−−−−−−−−−−−−−−^
// It's 2 because the first code point in the string occupies two code *units*

const array = [...theString].map(s => s.codePointAt(0));
console.log(array); // [127482, 127480]

或通过Array.from 及其映射回调跳过Sebastian Simon pointed out 的中间步骤:

const array = Array.from(theString, s => s.codePointAt(0));
console.log(array); // [127482, 127480]

例子:

const theString = String.fromCodePoint(...[127482, 127480]);

console.log(theString.codePointAt(0)); // 127482
console.log(theString.codePointAt(2)); // 127480

const array = [...theString].map(s => s.codePointAt(0));
console.log(array);  // [127482, 127480]

const array2 = Array.from(theString, s => s.codePointAt(0));
console.log(array2); // [127482, 127480]

Spread 和Array.from 都使用字符串iterator 工作,它通过代码点工作,而不是像大多数字符串方法那样工作的代码单元。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2019-09-22
    • 2022-11-02
    相关资源
    最近更新 更多