JavaScript code recipe: split string into array

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

Posted on January 27, 2021


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("");
console.log(arr);

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 😉

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more
JavaScript Introduction Book