If you want to split a string into an array of substrings, then JavaScript provides you the String.prototype.split()
method. The split() method accepts two optional arguments, separator, and limit.
The syntax for the split() method is:
let substringsArray = str.split(separator, limit);
The separator
is used to specify the condition based on which the string will be split. The separator can be a string or regular expression.
If you don't pass the separator, then the split() method returns the entire string.
The limit
> is used to specify the number of substrings that will be returned by the split() method. The limit is an optional argument, and it could be a zero or positive number.
Let's understand how to use the split() method by going through some examples.
When you want to split a string into words then a space character is used as a separator.
let str = 'I am learning JavaScript'; console.log(str.split(" "));
Output
["I", "am", "learning", "JavaScript"]
If you want to split a word into letters, then pass an empty string as a separator to the split() method.
let str = 'JavaScript'; console.log(str.split(""));
Output
["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]
The following example passes 3 to the limit argument. By doing this, the number of substrings will be limited to three.
let str = 'I am learning JavaScript'; console.log(str.split(" ", 3));
Output
["I", "am", "learning"]
It is important for you to know that you can pass a regular expression as a separator to the split() method.
The following example splits the paragraph into sentences:
let str = 'Hello Mohit! How are you?'; console.log(str.split(/[!?]/));
Output
["Hello Mohit", " How are you", ""]
If you want to include the characters based on which the string is split then surround that regular expression with a pair of parenthesis.
let str = 'Hello Mohit! How are you?'; console.log(str.split(/([!?])/));
Output
["Hello Mohit", "!", " How are you", "?", ""]