How to Split String Into Array in JavaScript

Harshit Jindal Feb 02, 2024
  1. Use the split() Method to Split a String Into an Array in JavaScript
  2. Use the from() Method to Split a String Into an Array in JavaScript
  3. Use ES6 spread Operator to Split a String Into an Array
How to Split String Into Array in JavaScript

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:

  1. object: It is the input object that is to be converted to an array.
  2. mapFunction: It is an optional argument specifying the map function to call on array items.
  3. thisValue: It is used to represent the this value of the object in the mapFunction.
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 avatar Harshit Jindal avatar

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.

LinkedIn

Related Article - JavaScript Array

Related Article - JavaScript String