Michael
Michael

Reputation: 151

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.

Upvotes: 2

Views: 716

Answers (2)

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.

Upvotes: 3

Boris Simeonov
Boris Simeonov

Reputation: 21

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);

Upvotes: 1

Related Questions