Introduction

The split() method splits a string into an array of substrings. It uses a pattern specified in the argument to divide the string into an ordered list of substrings.

let str = "Hello world!";

let arr = str.split(" ");
console.log(arr); // ['Hello', 'world!']

In the above example, we have split the string str using a space. The method looks for a single space in the string and splits them into substrings.

Now let’s add two spaces in between the two words,

let str = "Hello  world!";

let arr = str.split(" ");
console.log(arr); // ['Hello', '', 'world!']

Similarly,

let str = "Why was six afraid of seven? Because seven eight nine.";

let arr = str.split(" ");
console.log(arr); // ['Why', 'was', 'six', 'afraid', 'of', 'seven?', 'Because', 'seven', 'eight', 'nine.']

If you split the above string using ?

let str = "Why was six afraid of seven? Because seven eight nine.";

let arr = str.split("?");
console.log(arr); // ['Why was six afraid of seven', ' Because seven eight nine.']

arguments

The split() method takes two arguments. The first argument is the separator and the second one is limit. Both the arguments are optional.

separator: Separator is the pattern using which the string gets split. In the above examples we used space ” “ and ? as the separator to split the string.

limit: An integer to specify the number of splits. This will limit the number of substrings you want in an array.

Since both the arguments are optional, if you don’t specify any arguments the split method will enclose the entire string in an array.

let str = "I love JavaScript";

let arr = str.split();
console.log(arr); // ['I love JavaScript']

Using limit in split method

If you want to restrict the number of elements you want to have in an array, use the limit argument along with the split() method.

let str = "I love JavaScript";

let arr1 = str.split(" ");
console.log(arr1); // ['I', 'love', 'JavaScript']

let arr2 = str.split(" ", 2);
console.log(arr2); // ['I', 'love']

Using regular expressions in split()

You can also specify a regular expression as an argument in the spilt() method.

let str = "Why can't you trust an atom? Because they make up literally everything.";

let arr = str.split(/['\?]/);
console.log(arr); // ['Why can', 't you trust an atom', ' Because they make up literally everything.']