If an empty string (”) is used as the separator, the string is split between each character. The string split() method does not change an original string. The syntax for the split() method is following.
The separator is an optional parameter. The separator specifies a character, or a regular expression, to use for splitting a string. If omitted, then the entire string will be returned.
The limit is an optional parameter. It is an integer that specifies the number of splits, items after the split limit will not be included in the array.
// app.js let str = 'Obama was US president'; let result = str.split('was'); console.log(result);
So, in the above example, we have split the string from a was separator. So the output looks like this.
When found, the separator is removed from the string, and the substrings are returned in an array. If the separator is not found or is omitted, the array contains one element consisting of the entire string. If the separator is an empty string, a string is converted to an array of characters. If the separator appears at the beginning or end of a string, or both, then the array begins, ends, or both begins and ends, respectively, with the empty string. Thus, if a string consists solely of one instance of the separator, the array consists of two empty strings. If the separator is an array, then Array is coerced to String and used as a separator.
Returning a limited number of splits
Look at the following example.
// app.js let str = 'Obama was US president'; let result = str.split(' ', 3); console.log(result);
In the above example, we have set the limiter 3. So it will split and returns three elements of an array.
Split with a regular expression.
// app.js let str = 'Obama was US president'; let result = str.split(/(\d)/); console.log(result);