The split() method of the String class in JavaScript divides a string into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a specified separator string.
There are 2 variations for the syntax of String.split() method. They are:
split(separator)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
separator | optional | The pattern describing where each split should occur. Can be a string or a regular expression. If omitted, the entire string is returned in an array with a single element. |
This method splits the string at each occurrence of the specified separator and returns an array of substrings.
Returns value of type Array
.
split(separator, limit)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
separator | optional | The pattern describing where each split should occur. Can be a string or a regular expression. If omitted, the entire string is returned in an array with a single element. |
limit | optional | A non-negative integer specifying a limit on the number of splits. If provided, only the first limit splits are included in the array. |
This method splits the string at each occurrence of the specified separator and returns an array of substrings, limited to the specified number of splits.
Returns value of type Array
.
In JavaScript, we can use the split()
method to divide a string into an array of substrings using a specified separator.
For example,
str
with the value 'apple,banana,cherry'
.split()
method with the separator ','
.fruitArray
.fruitArray
to the console using console.log()
method.const str = 'apple,banana,cherry';
const fruitArray = str.split(',');
console.log(fruitArray);
['apple', 'banana', 'cherry']
In this example, we use the split()
method to divide a string into an array of substrings using a specified separator and limit the number of splits.
For example,
str
with the value 'apple,banana,cherry,dates'
.split()
method with the separator ','
and the limit 2
.fruitArray
.fruitArray
to the console using console.log()
method.const str = 'apple,banana,cherry,dates';
const fruitArray = str.split(',', 2);
console.log(fruitArray);
['apple', 'banana']
In this example, we use the split()
method without specifying a separator, resulting in an array with the entire string as a single element.
For example,
str
with the value 'Hello World'
.split()
method without any separator.wordArray
.wordArray
to the console using console.log()
method.const str = 'Hello World';
const wordArray = str.split();
console.log(wordArray);
['Hello World']
In this JavaScript tutorial, we learned about split() method of String: the syntax and few working examples with output and detailed explanation for each example.