gpt4 book ai didi

javascript - 在javascript中将文本转换为Unicode

转载 作者:行者123 更新时间:2023-11-30 07:44:45 27 4
gpt4 key购买 nike

我有以下内容:

function showUnicode()
{
var text = prompt( 'Enter the wanted text', 'Unicode' ),
unicode = 0,
ntext,
temp,
i = 0
;

// got the text now transform it in unicode
for(i; i < text.length; i++)
{
unicode += text.charCodeAt(i)

}

// now do an alert
alert( 'Here is the unicode:\n' + unicode + '\nof:\n' + text )

}

感谢初始化 unicode 的想法,但现在 unicode 变量获取最后一个字符的 Unicode,这是为什么?

最佳答案

JavaScript uses UCS-2 internally.

这意味着补充 Unicode 符号作为两个单独的代码单元(代理项的一半)公开。例如,'𝌆'.length == 2,即使它只是一个 Unicode 字符。

因此,如果您想获取字符串中每个字符的 Unicode 代码点,您需要将 UCS-2 字符串转换为 UTF-16 代码点数组(其中每个代理项对形成一个单个代码点)。你可以使用 Punycode.js的效用函数:

punycode.ucs2.decode('abc'); // [97, 98, 99]
punycode.ucs2.decode('𝌆'); // [119558]

关于javascript - 在javascript中将文本转换为Unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8915684/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com