Introduction
Textual data is typically stored through sequences of characters - strings. These sequences, are ultimately, arrays, and converting between the two structures typically is both simple and intuitive. Whether you're breaking a word down into its characters, or a sentence into words - splitting a string into an array isn't an uncommon operation, and most languages have built-in methods for this task.
In this guide, learn how to convert a String to an Array in JavaScript, with the
split()
,Object.assign()
,Array.from()
methods andspread[...]
operator, as well as when to use which.
Split String into Array with split()
The split()
method is used to divide a string into an ordered list of two or more substrings, depending on the pattern/divider/delimiter provided, and returns it. The pattern/divider/delimiter is the first parameter in the method's call and can be a regular expression, a single character, or another string.
If you'd like to learn more about Regular Expressions - read our Guide to Regular Expressions and Matching Strings in JavaScript!
For example, suppose we have a string:
let quote = 'I am unstoppable!';
We could split it on each whitespace (breaking it down into words), or on every character, or any other arbitrary delimiter, such as 'p'
:
// Split string using a whitespace
let array1 = quote.split(' ');
console.log(array1); // ["I", "am", "unstoppable!"]
// Splitstring using an empty string (on each character)
let array2 = quote.split('');
console.log(array2); // ["I", " ", "a", "m", " ", "u", "n", "s", "t", "o", "p", "p", "a", "b", "l", "e", "!"]
// Split string using a specific character
let array3 = quote.split('p');
console.log(array3); // ["I am unsto", "", "able!" ]
One of the major downsides of using single characters or even entire strings is that the approach is fairly rigid. You can't match by multiple delimiters, unless you use a Regular Expression. For instance, say you'd like to break a string into sentences. A sentence can end with a period (.
), exclamation mark (!
), a question mark (?
) or three dots (...
). Each of these are valid sentences, but we'd have to perform multiple splits to match all of them, if we were to use single characters or strings.
Pattern matching is where Regular Expressions excel! Let's split a string on each sentence, with any of these ending delimiters:
let text = "What a big family it was! That would be a big help. The big question was how to end it; Was he there? Terrible occurrence."
let sentences = text.split(/[.,!,?,;,...]/);
console.log(sentences); // ["What a big family it was", " That would be a big help", " The big question was how to end it", " Was he there", " Terrible occurrence", ""]
However, the delimiters are lost! We split on them and in the process, remove them from the output. Additionally, we have multiple whitespaces in the beginnings of the sentences, and there's an empty string in the end! This isn't to say that split()
doesn't work well with Regular Expressions - but it is to say that splitting sentences out of text isn't solved well by split()
. This is where we can use the match()
method instead - which returns the matching patterns and their delimiters:
let text = "What a big family it was! That would be a big help. The big question was how to end it; Was he there? Terrible occurrence."
let sentences = text.match(/[^.!?]+[.!?]+/g);
console.log(sentences); // ["What a big family it was!", " That would be a big help.", " The big question was how to end it; Was he there?", " Terrible occurrence." ]
Again, if you're interested in learning more about Regular Expressions - read our Guide to Regular Expressions and Matching Strings in JavaScript!
Note: The split()
method takes in a second parameter, which specifies the limit of splitting that can occur. It doesn't alter the number of splits and elements to fit the passed argument, but rather, performs the split n
times, from the start, and stops splitting after that.
To limit the number of splits we perform, we can easily supply the second argument of the split()
method:
let sentence = "The big question was how to end it";
let array = sentence.split(" ", 3);
console.log(array); // ["The","big","question"]
A common use case for the split()
method is when someone supplies their full name as a single string:
let name = "John Doe"
Here, we can split the name and save it as different fields of an object to the database, for instance:
// Split using a space character
let names = name.split(" ");
console.log(names); // ["John","Doe"]
// call names by array index
let firstName = names[0];
let lastName = names[1];
console.log(firstName); // "John"
console.log(lastName); // "Doe"
Instead of having to call get both elements using an array index, we can use array destructuring to make the assignment cleaner:
let [firstName, lastName] = name.split(' ');
console.log(firstName, lastName); //"John" "Doe"
Note: The split()
method doesn't support certain UTF-8 characters, such as emojis (i.e. 😄, 😍, 💗), and will replace them with a pair of ��
.
Split String into Array with Array.from()
The from()
method from the Array
class is the leading contender to the split()
method. It's used to create an array, given a source of data - and naturally, it can be used to create an array from an iterable string:
let name = "John Doe";
// String to array of chracters
let nameChars = Array.from(name);
console.log(nameChar); //["J","o","h","n"," ","D","o","e"]
// Manipulating array
let nameCharsReversed = nameChars.reverse().join('');
console.log(nameCharsReversed); //"eoD nhoJ"
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
The major benefit of using Array.from()
instead of split()
is that you don't have to bother with setting a delimiter - the constituent elements are just re-exposed and added to an array, rather than being converted explicitly. Additionally, the Array.from()
method supports emoji characters:
let word = "It is sweet 😋";
let wordChars = Array.from(word)
console.log(wordChars); // ["I","t"," ","i","s"," ","s","w","e","e","t"," ","😋"]
Split String into Array with the Spread Operator
The Spread Operator has several uses and is a widely-applicable operator in JavaScript. In our context - we'd be most interested in expanding arrays (strings are arrays of characters).
If you'd like to learn more about the Spread Operator - read our Spread Operator in JavaScript!
The operator's syntax is simple and clean - and we can spread out the string into an array:
let name = "John Doe";
// Spread out string into an array
let nameChar = [...name];
console.log(nameChar); //["J","o","h","n"," ","D","o","e"]
// Manipulating array
let nameCharReverse = nameChar.reverse().join('');
console.log(nameCharReverse); //"eoD nhoJ"
The operator also works with UTF-8 emojis:
let word = "It is sweet 😋";
let wordChar = [...word]
console.log(wordChar); // ["I","t"," ","i","s"," ","s","w","e","e","t"," ","😋"]
Split String with Object.assign()
The Object.assign()
method copies all values and properties of one object - and maps them to the properties of another. In a sense - it's used for cloning objects and merging those with the same properties:
Object.assign(target, ...sources)
In our case - we'd be copying and mapping the values within a string onto an array:
Object.assign([], string)
This approach is a bit more verbose, and less aesthetically pleasing than the previous two:
let name = "John Doe";
// Assigning string values to an array
let nameChar = Object.assign([], name);
console.log(nameChar); //["J","o","h","n"," ","D","o","e"]
// Manipulating array
let nameCharReverse = nameChar.reverse().join('');
console.log(nameCharReverse); //"eoD nhoJ"
It's worth noting that Object.assign()
doesn't support special UTF-8 characters such as emojis:
let word = "It is sweet 😋";
let wordChars = Object.assign([], word);
console.log(wordChars); // ["I","t"," ","i","s"," ","s","w","e","e","t"," ","�","�"]
Conclusion
In this short guide, we've taken a look at how to convert a string into an array in JavaScript. We've explored the split()
method, which has the highest level of customizability - including splitting on Regular Expressions! Then, we've explored the creation of arrays from()
sources such as strings. The Spread Operator works very well in expanding strings back to arrays, and we've finally covered the Object.assign()
method to assign the values of a string to an array.