split a string into an array of characters in javascript

You can use the split() method with an empty string as the separator to split a string into an array of individual characters in JavaScript:

index.tsx
const str = "hello";
const chars = str.split("");

console.log(chars); // ["h", "e", "l", "l", "o"]
100 chars
5 lines

In the code above, str is the string we want to split, and chars is the resulting array of characters. The split() method splits the string at every empty string (i.e. between each character), resulting in an array of individual characters.

You can also use the spread operator to convert the array-like object returned by split() into a proper array:

index.tsx
const str = "world";
const chars = [...str];

console.log(chars); // ["w", "o", "r", "l", "d"]
95 chars
5 lines

In this case, the ... (spread) operator expands the array-like object returned by split() into a proper array. This has the same effect as using the Array.from() method.

gistlibby LogSnag