JavaScript String split() Method. Split a String into an Array

JavaScript String split() method is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument.

Syntax:

str.split(separator, limit)
  • separator: It is used to specifie the character, or the regular expression, to use for splitting the string. If the separator is unspecified then the entire string becomes one single array element. The same also happens when the separator is not present in the string. If the separator is an empty string (“”) then every character of the string is separated.
  • limit: Defines the upper limit on the number of splits to be found in the given string. If the string remains unchecked after the limit is reached then it is not reported in the array.

Return value
This function returns an array of strings that is formed after splitting the given string at each point where the separator occurs.

Example 1:

var str = 'You are the best';
var array = str.split(" ");
console.log(array);

Output

["You", "are", "the", "best"]

In this example the function split() creates an array of strings by splitting str wherever ” “ occurs.

How to add a limit to split

According to the MDN, it is also possible to pass a limit as an argument to split. I have never needed to do this, but here is how you could apply it:

const publisher = 'free code camp'
publisher.split(' ', 1) // [ 'free' ]

How to split string using regular expression?

We can also use the regular expression to split string.

Syntax:

str.split(regexp|substr, limit)

The following example uses the split() method to split sentences in a paragraph into sentences:

let paragraph = 'Good Morning! How are you? This is John. John is my friend.'; let sentences = paragraph.split(/[!,?,.]/); 
console.log(sentences);

Output:

["Good Morning", " How are you", " This is John", " John is my friend", ""]

If the regular expression contains capturing parentheses (), the split() method also includes the matched results in the array:

let paragraph = 'Good Morning! How are you? This is John. John is my friend.'; let sentences = paragraph.split(/([!,?,.])/); 
console.log(sentences);

Output:

["Good Morning", "!", " How are you", "?", " This is John", ".", " John is my friend", ".", ""]