How to convert string to character Array in JavaScript?

Convert string to a character Array in JavaScript

Using modern JavaScript you can easily convert a string to a character array in a variety of ways.

Here is a list of a few ways to do this –

  • String.split() method
  • Array.from() method
  • [...String] spread operator
const a_name = "John";

const a = a_name.split('');
const b = Array.from(a_name);
const c = [...a_name];

console.log(a,b,c);
[ 'J', 'o', 'h', 'n' ] [ 'J', 'o', 'h', 'n' ] [ 'J', 'o', 'h', 'n' ]

String.split() method

The string split() method returns an array that contains UTF-16 “characters”. But, Emojis are from the UTF-8 character set.

So If you are using the split method with a string that contains emojis, then you will face the following problem –

const fruit = "Apple 🍎";

const a = fruit.split('');

console.log(a);
[ 'A', 'p', 'p', 'l', 'e', ' ', '\ud83c', '\udf4e' ]

In the above array, the apple emoji is converted to UTF-16 Unicode. But, you can see there are two Unicodes '\ud83c', and '\udf4e'. It is because the apple emoji is made up of 2 characters –

const fruit = "🍎";

console.log(fruit.length);
2

How to solve this emoji problem?

Solution 1: Use the Array.from() method or spread operator instead of the split() method.

const fruit = "Hi 🍎";

const a = Array.from(fruit);
const b = [...fruit];

console.log(a, b);
[ 'H', 'i', ' ', '🍎' ] [ 'H', 'i', ' ', '🍎' ]

Solution 2: use the regexp with the u flag, only then the split method will work.

const fruit = "Hi 🍎";

const a = fruit.split(/(?:)/u)

console.log(a);
[ 'H', 'i', ' ', '🍎' ]