How to Split String Into Array in JavaScript
-
Use the
split()
Method to Split a String Into an Array in JavaScript -
Use the
from()
Method to Split a String Into an Array in JavaScript -
Use ES6
spread
Operator to Split a String Into an Array
This tutorial teaches how to split a string into an array in JavaScript.
Use the split()
Method to Split a String Into an Array in JavaScript
The 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);
Output:
["d", "e", "l", "f", "t", "s", "t", "a", "c", "k"]
Use the from()
Method to Split a String Into an Array in JavaScript
The 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 thethis
value of the object in themapFunction
.
console.log(Array.from('delftstack'));
Use ES6 spread
Operator to Split a String Into an Array
The 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.
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.
LinkedInRelated Article - JavaScript Array
- How to Check if Array Contains Value in JavaScript
- How to Create Array of Specific Length in JavaScript
- How to Convert Array to String in JavaScript
- How to Remove First Element From an Array in JavaScript
- How to Search Objects From an Array in JavaScript
- How to Convert Arguments to an Array in JavaScript