Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot get utf8 icon with charAt js

let a=["๐Ÿ˜"] ;
let b="๐Ÿ˜"

console.log(a[0],b,b.charAt(0))

"๐Ÿ˜"
"๐Ÿ˜"
"๏ฟฝ"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this charAt prints questions mark … can someone enlighten me how to get utf8 icon with charAt in a string

>Solution :

Emojis are represented using multiple bytes:

let b="๐Ÿ˜"
console.log(b.length)

With charAt you only get one part of the emoji.

With codePoint you can get the:

a non-negative integer that is the Unicode code point value at the given position.

You however need to know where the emojii starts at, because the index itself still refers to the bytes:

let b="๐Ÿ˜๐Ÿ‘†๐Ÿ‘"
console.dir(String.fromCodePoint(b.codePointAt(0)));
console.dir(String.fromCodePoint(b.codePointAt(2)));

You could split your string using the spread operator ... and then access the visible char in question using the index. This works because the iterator uses the code points and not individual bytes.

let b="๐Ÿ˜test๐Ÿ‘†test๐Ÿ‘"

function splitStringByCodePoint(str) {
  return [...str]
}

console.log(splitStringByCodePoint(b)[5])

But that won’t work with emojis like ๐Ÿ‘†๐Ÿฝ because those consist of ๐Ÿ‘† + byte(s) representing the variation (color).

let b="๐Ÿ‘†๐Ÿฝ"
console.log(b.length)
function splitStringByCodePoint(str) {
  return [...str]
}

console.log(splitStringByCodePoint(b))
console.log(String.fromCodePoint(b.codePointAt(0)));
console.log(String.fromCodePoint(b.codePointAt(2)));

If you want to support all emojis you currently need to write your own parser or look for a library that does that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading