Aral Balkan

Mastodon icon RSS feed icon P2P network icon

Get Unicode-aware length of string in JavaScript

stringInstance.length in JavaScript is not Unicode aware.

That means, for example, that the following code:

"šŸ¤“".length

Will return 2, not 1.

If you want a Unicode-aware string length, use this function:

function unicodeLength(str) {
  return [...str].length
}

Using that function, the following code:

unicodeLength("šŸ¤“")

Will return 1.

References