我想使用索引从 unicode 字符串中获取特定字母。但是,它并没有按预期工作。
示例:
var handwriting = `𝖆𝖇𝖈𝖉𝖊𝖋𝖌𝖍𝖎𝖏𝖐𝖑𝖒𝖓𝖔𝖕𝖖𝖗𝖘𝖙𝖚𝖛𝖜𝖝𝖞𝖟𝕬𝕭𝕮𝕯𝕰𝕱𝕲𝕳𝕴𝕵𝕶𝕷𝕸𝕹𝕺𝕻𝕼𝕽𝕾𝕿𝖀𝖁𝖂𝖃𝖄𝖅1234567890`
var normal = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`
console.log(normal[3]) // gives 'd' but
console.log(handwriting[3]) // gives '�' instead of '𝖉'
长度也无法按预期工作normal.length
给出正确的值,如62,但handwriting.length
给出114。
索引未按预期工作。如何访问 unicode 数组的元素?
我在 python 上尝试过,它工作得很好,但在 Javascript 中却不起作用。
我需要 unicode 字符串中的精确字符,例如索引 3 的“d”“𝖉”的预期输出
最佳答案
In Javascript, a string is a sequence of 16-bit code points. Since these characters are encoded above the Basic Multilingual Plane, it means that they are represented by a pair of code points, also known as a surrogate pair.
𝖆
的Unicode编号是U+1D586
。并且 0x1D586 大于 0xFFFF (2^16)。因此,𝖆
由一对代码点表示,也称为代理对
console.log("𝖆".length)
console.log("𝖆" === "\uD835\uDD86")
一种方法是使用展开语法或 Array.from()
创建字符数组,然后获取所需的索引
var handwriting = `𝖆𝖇𝖈𝖉𝖊𝖋𝖌𝖍𝖎𝖏𝖐𝖑𝖒𝖓𝖔𝖕𝖖𝖗𝖘𝖙𝖚𝖛𝖜𝖝𝖞𝖟𝕬𝕭𝕮𝕯𝕰𝕱𝕲𝕳𝕴𝕵𝕶𝕷𝕸𝕹𝕺𝕻𝕼𝕽𝕾𝕿𝖀𝖁𝖂𝖃𝖄𝖅1234567890`
console.log([...handwriting][3])
console.log(Array.from(handwriting)[3])
关于javascript - 如何从 unicode 字符串中获取正确的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56390275/