'Javascript check if character is 32bit
Using javascript, i want to check if a certain character is 32 bit or not ? How can i do it ? I have tried with charCodeAt() but it didn't work out for 32bit characters.
Any suggestions/help will be much appreciated.
Solution 1:[1]
The charCodeAt() docs returns integer between 0 to 65535 (FFFF) representing UTF-16 code unit.
If you want the entire code point value, use codePointAt().
You can use the string.codePointAt(pos) to easily check if a character is represented by 1 or 2 code point value .
Values greater than FFFF means they take 2 code units for a total of 32 bits.
function is32Bit(c) {
return c.codePointAt(0) > 0xFFFF;
}
console.log(is32Bit("?")); // true
console.log(is32Bit("a")); // false
console.log(is32Bit("?")); // false
Note: codePointAt() is provided in ECMAScript 6 so this might not work in every browser. For ECMAScript 6 support, check firefox and chrome.
Solution 2:[2]
function characterInfo(ch) {
function is32Bit(ch) {
return ch.codePointAt(0) > 0xFFFF;
}
let result = `character: ${ch}\n` +
`CPx0: ${ch.codePointAt(0)}\n`;
if(ch.codePointAt(1)) {
result += `CPx1: ${ch.codePointAt(1)}\n`;
}
console.log( result += is32Bit(ch) ?
'Is 32 bit character.' :
'Is 16 bit character.');
}
//For testing
let ch16 = String.fromCodePoint(10020);
let ch32 = String.fromCodePoint(134071);
characterInfo(ch16);
characterInfo(ch32);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohsen Alyafei |
| Solution 2 | Boris Simeonov |
