Split String Into Array in JavaScript

Split String Into Array in JavaScript

  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

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.

Related Article - JavaScript Array

  • Check if Array Contains Value in JavaScript
  • Create Array of Specific Length in JavaScript
  • Convert Array to String in JavaScript
  • Remove First Element From an Array in JavaScript
  • Search Objects From an Array in JavaScript
  • Convert Arguments to an Array in JavaScript
  • Related Article - JavaScript String

  • Get Last Character of a String in JavaScript
  • Convert a String Into a Date in JavaScript
  • Get First Character From a String in JavaScript
  • Convert Array to String in JavaScript
  • Check String Equality in JavaScript
  • Filter String in JavaScript