'Is there a way to know the number of characters in a string?

This question concerns unicode characters that are more than one utf-16 character

string.length returns the number of unicode 16 chars in the string. But what about the case of characters that are more than 1 unicode 16 character? Is it possible to get the actual number of characters as well as "true" values from string.charAt of the actual character, and not the utf-16 pieces?

var test = "🀄";
console.log(test.length)
var regex = /[\u{1F000}-\u{1F0FF}]/g;
var regex2 = /🀄/g
console.log('test: ' + regex.test(test));
console.log('test2: ' + regex2.test(test));


Solution 1:[1]

Another option is to use RegExp with the unicode flag.

var test = "?";
var length = test.match(/./ug).length;
console.log(length);

Please note that this and the answer using the spread operator can break under certain circumstances.

var test = "Z??????????????????A????????L?????G????????????O??????????";
var length = test.match(/./ug).length;
console.log(length);

To get the char at a specific index you can use the following function.

var test = "????";

var charAt = charAt(test);

console.log(charAt);

function charAt(string, index) {
    if(!index)
        index = 0;

    return string.match(/./ug)[index];
}

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