How can I get a character array from a string?
To convert a string into a character array, use either Array.from(str)
or the spread operator [...,str]
:
Beware! Unicode monsters
While working with Unicode characters in JavaScript, be vigilant. Invoking .split('')
may result in disruptions when surrogate pairs come into play.
Desired output with Array.from()
:
Terrifying output with .split('')
:
See, the .split('')
mechanism fails to acknowledge surrogate pairs and disrupts the Unicode characters.
Taming Unicode with regex
To properly handle Unicode characters, employ a regular expression with the u
(Unicode) flag in conjunction with split
:
Iterating with 'for ... of ...'
To maintain the integrity of Unicode characters, consider using a for...of
loop, that inherently caters to Unicode:
So, peace
now comfortably contains ['🌍', '🕊️']
.
Check compatibility before dating ES6
Before you use cool ES6 features like the spread operator or Array.from()
, ensure your JavaScript environment won't ghost you. Check the ECMAScript compatibility table or MDN for this.
Coping with complex characters using libraries
The grapheme-splitter library serves as a good companion when facing complex character sequences, like emoji flags, family emojis, etc.
Performance tales with massive strings
When countering massive strings, Array.from
and spread syntax may betray you performance-wise. In such cases, a good-old for...of
loop might act as a knight in shining armor.
Jamming with tokens in older environments
To seamlessly work in non-ES6 environments, combine the character access method charAt
with a basic loop:
Although this won't respect Unicode integrity, it promises wide support.
The peril of split('')
with multi-code-unit characters
split('')
treats multi-code-unit characters, like certain emojis or specific foreign language characters, as separate units, which brings undesired results.
Was this article helpful?