如何在 Javascript 中获取字符的 Unicode 代码点? [英] How to get the Unicode code point for a character in Javascript?

查看:37
本文介绍了如何在 Javascript 中获取字符的 Unicode 代码点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用条码扫描器读取我网站上的条码(该网站是在 OpenUI5 中制作的).

I'm using a barcode scanner to read a barcode on my website (the website is made in OpenUI5).

扫描仪的工作原理类似于键盘,可以输入它读取的字符.在打字的结尾和开头,它使用一个特殊字符.每种类型的扫描仪的这些字符都不同.

The scanner works like a keyboard that types the characters it reads. At the end and the beginning of the typing it uses a special character. These characters are different for every type of scanner.

一些可能的字符是:

  • ——

在我的代码中,我使用 if (oModelScanner.oData.scanning && oEvent.key == "u2584") 来检查来自扫描仪的输入是否为 ▄.

In my code I use if (oModelScanner.oData.scanning && oEvent.key == "u2584") to check if the input from the scanner is ▄.

有什么办法可以从 uHHHH 样式中的那个字符中获取代码?(其中 HHHH 为字符的十六进制代码)

Is there any way to get the code from that character in the uHHHH style? (with the HHHH being the hexadecimal code for the character)

我尝试了 charCodeAt 但这会返回十进制代码.

I tried the charCodeAt but this returns the decimal code.

使用 codePointAt 示例他们把我需要的代码变成了十进制代码,所以我需要反过来.

With the codePointAt examples they make the code I need into a decimal code so I need a reverse of this.

推荐答案

Javascript 字符串有一个方法 codePointAt 它为您提供表示 Unicode 点值的整数.如果您希望将整数格式化为四个十六进制数字序列(如 Nikolay Spasov 的回复),您需要使用该数字的基数 16(十六进制)表示.

Javascript strings have a method codePointAt which gives you the integer representing the Unicode point value. You need to use a base 16 (hexadecimal) representation of that number if you wish to format the integer into a four hexadecimal digits sequence (as in the response of Nikolay Spasov).

var hex = "▄".codePointAt(0).toString(16);
var result = "\u" + "0000".substring(0, 4 - hex.length) + hex;

但是,如果您的关键代码点整数与预期的代码点匹配,直接检查可能会更容易

However it would probably be easier for you to check directly if you key code point integer match the expected code point

oEvent.key.codePointAt(0) === '▄'.codePointAt(0);

注意符号相等"实际上可能更棘手:某些符号由代理对定义(您可以将其视为定义为四个十六进制数字序列的两半的组合).

Note that "symbol equality" can actually be trickier: some symbols are defined by surrogate pairs (you can see it as the combination of two halves defined as four hexadecimal digits sequence).

出于这个原因,我建议使用专门的库.

For this reason I would recommend to use a specialized library.

您会在非常相关文章中找到更多详细信息,Mathias Bynens

这篇关于如何在 Javascript 中获取字符的 Unicode 代码点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆