6 Ways to Convert a String to an Array in JavaScript
Tags: javascript, webdev, programming
Published: 2022-09-24 07:50:08

Arrays are the most powerful data structure in JavaScript. I found myself solving many algorithms by converting strings to arrays. So I thought of consolidating and comparing various ways to do the same.

Converting from string to array is always done using the split() method but after ES6, there are many tools we could do the same. Let’s go through each method one by one and discuss the pros and cons of each.

###1. Using .split(‘’):
`split()` is a string method that splits a string into an array of the ordered list with a pattern. This is an ES6 method and is the cleanest way to get the job done.

```javascript
////* Seperate string by space character(' ') *////

const myFavShow = 'The Office';
const myFavShowArray = myFavShow.split('');
console.log(myFavShowArray) 
//['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']
```
Another advantage of this way is we can separate strings by characters or whitespace. Below is an example of how we can do it.
```javascript
////* Seperate string by whitespace(' ') *////
const myFavShow = 'The Office';
const myFavShowArray = myFavShow.split(' ');
console.log(myFavShowArray) //['The', 'Office']

////* Seperate string by a character '-' *////
const favDialogue = 'Thats-what-she-said';
const favDialogueArr = favDialogue.split('-');
console.log(favDialogueArr) //['Thats', 'what', 'she', 'said']
```
It also works well with Regex too. You can find the complete documentation of `split()` [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#specifications).

This way flawlessly separates the string elements into an array but it has its limitations.

> NOTE: This method does not work very well with uncommon Unicode characters. This method returns the Unicode of the characters instead of actual characters which might make our job a bit more complicated(refer [here](https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402)) but the MDN document has been updated so that we can make it work with Unicode if we just include u flag. See [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#description) for more information.

```javascript
"😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ]
"😄😄".split(/(?:)/u); // [ "😄", "😄" ]
```

###2. Using spread syntax ([…str])
This is the ES2015 feature that makes the transition very easy.

```javascript
const myFavShow = 'The Office'

const myFavShowArray = [...myFavShow]

console.log(myFavShowArray) 
// ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']
```

It also helps that the limitation we have in the `split()` has been eliminated here. Consider the below example. We can split any characters easily using this method.

```javascript
const animal = '🦊🦊'
const animalArr = [...animal]
console.log(animalArr) // ['🦊', '🦊']
```

###3. Using Array.from(str):
The `Array. from()` method creates a new, shallow-copied Array instance from an iterable or array-like object.

```javascript
const myFavShow = 'The Office'

const myFavShowArray = Array.from(myFavShow);

console.log(myFavShowArray) 
// ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']
```
This method will not cause any issues when dealing with uncommon characters.
```javascript
const str = '😎😎'
const arr = Array.from(str)
console.log(arr)


// ['😎', '😎']
```
###4. Using Object.assign([], str)
The `Object. assign()` method copies all the properties from one or more source objects to a target object. There are two things to keep in mind about this method though. One is that `Object. assign()` copies property values called deep copy (Refer here to know the difference between deep copy and shallow copy). One has to keep this in mind before using this method before using it.

```javascript
const myFavShow = 'The Office'

const myFavShowArray = Object.assign([], myFavShow);

console.log(myFavShowArray) 
// ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']
```
Another is that we have the same trouble as the `split()` method: it cannot separate uncommon characters (we see Unicode instead of actual characters).

```javascript
const s = '😄😄'
const a = Object.assign([], s);
console.log(a) // ['\uD83D', '\uDE04', '\uD83D', '\uDE04']
```
###5. Using old school method (`for loop` and `array.push()`)
Although we have a lot of options to play around with, I had to mention this old-school method where we push the elements of the string using the for loopand array method push().

This is not the cleanest way of doing it but it is most definitely worth mentioning who want to stay away from the changing complexities of JavaScript (Although I would prefer other ways).
```javascript
const s = 'the office';
const a = [];
for (const s2 of s) {
   a.push(s2);
}
console.log(a); 
// ['t', 'h', 'e', ' ', 'o', 'f', 'f', 'i', 'c', 'e']
```
Also, it works very well with uncommon (Unicode) characters. Look at the below example.
```javascript
const s = '𝟘𝟙𝟚𝟛😄😄';
const a = [];
for (const s2 of s) {
   a.push(s2);
}
console.log(a); //['𝟘', '𝟙', '𝟚', '𝟛', '😄', '😄']
```

###6. Using Array.prototype.slice.call(‘string’)
Refer to this [blog](https://www.stevenchang.tw/blog/2020/05/23/JavaScript-slice-call-function) to understand more about .slice.call()method.
```javascript
const favShow = Array.prototype.slice.call("The Office!");
console.log(favShow); //['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e', '!']
```
This method also has the same problem as the `split()` method so be aware while using it.
```javascript
const favShow = Array.prototype.slice.call("😄😄");
console.log(favShow); //['\uD83D', '\uDE04', '\uD83D', '\uDE04']
```
###References:
- https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character
- https://stackoverflow.com/questions/4547609/how-to-get-character-array-from-a-string/34717402#34717402
- https://www.stevenchang.tw/blog/2020/05/23/JavaScript-slice-call-function
- [MDN Web Docs: split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)
- [MDN Web Docs: spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)
- [MDN Web Docs: Array.from](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
- [MDN Web Docs: Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
- https://www.samanthaming.com/tidbits/83-4-ways-to-convert-string-to-character-array

###Conclusion:
To sum it all up, below are the ways we can do the job.

![Consolidated ways](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v0azr7yqbvgbzir4x3hf.png)

That’s 6 ways to convert string to array in JavaScript. Comment below if you used any other methods to get the job done.

Thank you for reading!