JavaScript code recipe: split string into array

Posted on Jan 27, 2021

Tutorial on how to split a string into an array in JavaScript with code examples.

Sometimes, you need to create an array that represents your string for your JavaScript program. You can create an array that represents your string data by using the split method, which is available for all string data types.

The split method accepts two arguments:

  • separator — Optional — specifies the character or regular expression used for splitting the string. If not present, the method will return a single array
  • limit — Optional — specifies the integer used for limiting the returned array. The array length for the returned value will be capped at this number
let str = "Banana";
let arr = str.split("");

The output will be as follows:

> Array ["B", "a", "n", "a", "n", "a"]

You can use the split method for any kind of value as long as it’s a string:

"Apple".split(); // ["Apple"]
"Apple".split("", 3); // ["A", "p", "p"]
true.split(""); //Uncaught TypeError: true.split is not a function

If you have a string with commas, you can pass them as the separator argument for the split method:

let arr = "Banana,Apple,Grape,Melon".split(",");
console.log(arr); // ["Banana", "Apple", "Grape", "Melon"]

Or you can also use a space:

let arr = "Banana Apple Grape Melon".split(" ");
console.log(arr); // ["Banana", "Apple", "Grape", "Melon"]

And that’s how you can split a string into an array 😉

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.