JavaScript – Convert String to Array
Here are the different methods to convert a string to an array in JavaScript.
1. Using String.split() Method
The split() method is the most commonly used approach to convert a string into an array based on a delimiter.
const s = "Hello World";
const a = s.split(" ");
console.log(a);
Output
[ 'Hello', 'World' ]
To split into individual characters
const s = "Hello";
const a = s.split("");
console.log(a);
Output
[ 'H', 'e', 'l', 'l', 'o' ]
2. Using Spread Operator
The spread operator (…) spreads a string into an array of individual characters.
const s = "Hello";
const a = [...s];
console.log(s);
Output
Hello
This is a concise way to achieve the same result as split(“”).
3. Using Array.from() Method
Array.from() creates an array from a string.
const s = "Hello";
const a = Array.from(s);
console.log(a);
Output
[ 'H', 'e', 'l', 'l', 'o' ]
You can also use a mapping function directly with Array.from()
const s = "Hello";
const a = Array.from(s, char => char.toUpperCase());
console.log(a);
Output
[ 'H', 'E', 'L', 'L', 'O' ]
4. Using slice() Method
The slice() method can be used with call() to convert a string to an array of characters.
const s = "Hello";
const a = Array.prototype.slice.call(s);
console.log(a);
Output
[ 'H', 'e', 'l', 'l', 'o' ]
This is a less commonly used method but works effectively.
5. Using Array.prototype.map() Method
You can map over a string by converting it to an array first.
const s = "Hello";
const a = [...s].map(char => char.toUpperCase());
console.log(a);
Output
[ 'H', 'E', 'L', 'L', 'O' ]
This is particularly useful when you want to manipulate elements during the conversion.
7. Naive Method
Using a loop to manually push characters into an array.
const s = "Hello";
const a = [];
for (const char of s) {
a.push(char);
}
console.log(a);
Output
[ 'H', 'e', 'l', 'l', 'o' ]
Which Approach Should You Use?
| Approach | When to Use |
|---|---|
| String.split() | Best for splitting strings based on a specific delimiter (e.g., spaces, commas). |
| Spread Operator | Quick and simple for breaking a string into characters. |
| Array.from() | Flexible for converting strings and applying transformations. |
| slice() | Works effectively but is less commonly used for this purpose. |
| Array.prototype.map() | Ideal when mapping or transforming the characters is required. |
| Naive Method | Use when manual control is needed. |


