- Instant help with your JavaScript coding problems

Convert string to character array in JavaScript

Question:
How to convert string to character array in JavaScript?
Answer:
function toCharArray(str) {
    return [...str];
}

console.log(toCharArray('this is my text'));
console.log(toCharArray('Spec éáőú and 💡✨'));
Description:

By default, if you want to convert a string into a character array in vanilla JavaScript you maybe think of the split function at first. Like this:

str.split('');

However, when using an empty string as a separator the split function uses UTF-16 code units and this ruins Unicode characters built up from 2 elements, for example:

console.log('Spec text 💡✨'.split(''));

Gives the result:

['S','p','e','c',' ','t','e','x','t',' ','\uD83D','\uDCA1','✨']

Solution

A better and even simpler solution is to simply use an array spread operator like this:

console.log([...'Spec text 💡✨']);

where the result will be the expected:

['S','p','e','c',' ','t','e','x','t',' ','💡','✨']

So that's a simple way to convert a string into a character array in modern JavaScript.

Share "How to convert string to character array in JavaScript?"