javascriptstringunicodesurrogate-pairsastral-plane

Get last character of string in current modern Javascript, allowing for Astral characters such as Emoji that use surrogate pairs (two code units)


Unicode characters (code points) not in the Basic Multilingual Plane (BMP) may consist of two chars (code units), called a surrogate pair.

'ab' is two code units and two code points. (So two chars and two characters.)

'a💩' is three code units and two code points. (So three chars and two characters.)

My code does not need to work with old versions of JavaScript. ES6 or whatever is most modern.

How can I access the last character, irrespective of whether its an Astral character or not?

Splitting the string into "all but last character" and "final character" is also fine.


Solution

  • Spreading will dissect a string into its code points

    [...'a💩'].pop()