How to Convert Strings to Arrays in JavaScript

You’ll want to know how to convert a string to an array in JavaScript if you’re handling user inputs or manipulating text data. It’s straightforward thanks to JavaScript's built-in methods, like splitting a string by a delimiter, using a regular expression for complex patterns, or breaking down a string into individual characters. Read the guide below to explore string to array conversions.

How to use the split method in JavaScript?

The split method is your go-to for converting a string into an array. It splits a string into an array of strings by separating it into substrings.

let myString = "Hello, world!"; let myArray = myString.split(", "); console.log(myArray); // Output: ["Hello", "world!"]

Splitting by a character

Split a string by every instance of a specified character to get an array of substrings. This is especially useful for processing comma-separated values.

let names = "John,Doe,Jane,Doe"; let namesArray = names.split(","); console.log(namesArray); // Output: ["John", "Doe", "Jane", "Doe"]

Splitting by regular expression

Use a regular expression as the separator for more complex splitting logic. This approach is beneficial when you need to split by multiple characters or patterns.

let data = "name: John; age: 30; occupation: developer"; let dataArray = data.split(/[:;]\\s*/); console.log(dataArray); // Output: ["name", "John", "age", "30", "occupation", "developer"]

Splitting into individual characters

To split a string into an array of its individual characters, simply use an empty string ('') as the separator.

let word = "hello"; let letters = word.split(''); console.log(letters); // Output: ["h", "e", "l", "l", "o"]

Considerations

  • Using the split method creates a new array without altering the original string.
  • If the separator does not appear in the string, you'll get an array containing the entire original string as its only element.
  • While regular expressions are powerful for splitting strings, they should be used judiciously as they can affect both performance and readability if overly complex.

Invite only

We're building the next generation of data visualization.