JavaScript How to Convert String to Array Easily
split() method to convert a string to an array in JavaScript, for example: const arr = str.split(''); splits the string into an array of characters.Examples
How to Think About It
split() method breaks the string into parts based on the separator you give it, returning an array of those parts.Algorithm
Code
const str1 = "hello"; const arr1 = str1.split(''); console.log(arr1); const str2 = "apple,banana,orange"; const arr2 = str2.split(','); console.log(arr2);
Dry Run
Let's trace converting "apple,banana,orange" to an array using split(',')
Input string
"apple,banana,orange"
Split by comma
Call split(',') on the string
Resulting array
["apple", "banana", "orange"]
| Iteration | Current Part |
|---|---|
| 1 | apple |
| 2 | banana |
| 3 | orange |
Why This Works
Step 1: Using split() method
The split() method divides the string into pieces wherever it finds the separator you give it.
Step 2: Separator choice
If you use an empty string '' as separator, it splits into single characters; if you use a comma ',', it splits at commas.
Step 3: Returns an array
The method returns a new array containing all the parts after splitting.
Alternative Approaches
const str = "hello"; const arr = Array.from(str); console.log(arr);
const str = "hello"; const arr = [...str]; console.log(arr);
Complexity: O(n) time, O(n) space
Time Complexity
The split() method scans the entire string once, so time grows linearly with string length.
Space Complexity
It creates a new array holding all parts, so space used is proportional to the number of parts.
Which Approach is Fastest?
split(''), Array.from(), and spread operator all run in linear time; split() is best for splitting by separators, others are simpler for characters.
| Approach | Time | Space | Best For |
|---|---|---|---|
| split(separator) | O(n) | O(n) | Splitting by any separator |
| Array.from() | O(n) | O(n) | Converting string to array of characters |
| Spread operator | O(n) | O(n) | Converting string to array of characters |
split('') to get characters or split(',') to split by commas.split() results in the whole string as one array element.