JavaScript(JS) string method - split
The split()
method is a string method in JavaScript that is used to split a string into an array of substrings based on a specified separator.
Here is the syntax for the split()
method:
str.split(separator, limit)
Here, str
is the string you want to split, separator
is the character or string you want to use as the separator, and limit
is an optional parameter that specifies the maximum number of splits to perform.
The split()
method returns an array of substrings that are separated by the separator
.
If the separator
is not specified, the split()
method splits the str
into an array of characters.
If the limit
is specified, the split()
method will perform at most limit
splits. The resulting array will have at most limit + 1
elements.
Here is an example of using the split()
method:
let str = "hello,world"; let result = str.split(","); console.log(result); // ["hello", "world"]
In the example above, the split()
method splits the str
into an array of two substrings, "hello" and "world", based on the separator ",".
If the separator is an empty string, the split()
method will split the str
into an array of single characters.
Here is an example of using the split()
method with an empty separator:
let str = "hello world"; let result = str.split(""); console.log(result); // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
In the example above, the split()
method splits the str
into an array of 11 substrings, each of which is a single character in the original string.