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 arraylimit
— 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"]
More on JavaScript: