spreadOperator to Split a String Into an Array
split() method takes as input a string and returns an array of substrings that are formed based on a delimiter. This splitting condition is provided as the first argument to the function. If we give no arguments, then we get an array containing a copy of the string. If we provide a delimiter, the function splits the string into an array of substrings separated by that character. So, if we want to get every character as an array element, we must provide
"" as an argument.
var arr = "delftstack".split(''); console.log(arr);
["d", "e", "l", "f", "t", "s", "t", "a", "c", "k"]
from() method takes as input an array and returns another array. If we provide a string as input, it creates an array with every character of the string as an array element. It takes the following parameters as arguments:
object: It is the input object that is to be converted to an array.
mapFunction: It is an optional argument specifying the map function to call on array items.
thisValue: It is used to represent the
thisvalue of the object in the
spread Operator to Split a String Into an Array
spread operator unpacks iterable objects. It iterates over any iterable object and expands it in place. When the spread operator is used on a string, we get an array of substrings where each substring is an individual character of the string.
const str = 'delftstack'; const arr = [...str]; console.log(arr);
Browsers like Internet Explorer do not support this operator.