Description
The JavaScript String method split()
divides a string into a list of substrings and returns them as an array.
- It generates and returns a new string, and it doesn't modify the original string.
- It splits a string at each occurrence of the separator.
Syntax
The method split()
has the below syntax, where str
is a string.
str.split(separator, limit)
Parameters
The method split()
allows the below parameters.
separator
(optional)
- It is a pattern (a string or a regular expression) for defines where each split should occur.
limit
(optional)
- It is a non-negative integer that limits the number of splits.
Result
Returns an array of strings by dividing the string into pieces based on the separator.
It doesn't modify the original string.
Example 1: Using the Method
The below example shows the basic usage of the method.
var str = "Hello World!";
// Without a separator
document.write(str.split()); // Prints: ['Hello World!']
// Using blank value as a separator
document.write(str.split("")); // Prints: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
// Using space as a separator
document.write(str.split(" ")); // Prints: ['Hello', 'World!']
Output:
['Hello World!']
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
['Hello', 'World!']
Example 2: Using the Method with Limit
If we want to limit the number of elements in an output array, we need to use the method with a limit.
var str = "Learning JavaScript is fun";
// Without limit
document.write(str.split(" ")); // Prints: ['Learning', 'JavaScript'. 'is', 'fun']
// With limit
document.write(str.split(" ", 2)); // Prints: ['Learning', 'JavaScript']
Output:
['Learning', 'JavaScript', 'is', 'fun']
['Learning', 'JavaScript']
Example 3: Splitting a Paragraph into Sentences
If we need to split a paragraph into sentences, we can easily do that by using the period (or a dot) as a separator.
var para = "Learning JavaScript is fun. It is easy to learn JavaScript. JavaScript and Java are different and not related.";
// Without a separator
document.write(para.split("."));
Output:
['Learning JavaScript is fun', ' It is easy to learn JavaScript', ' JavaScript and Java are different and not related', '']
Example 4: Using Regular Expression as a Separator
If we need to split a string based on a pattern, then we need to use a regular expression.
var str = "HTML, CSS , JavaScript, Java, C, C++";
var pattern = /\s*(?:,|$)\s*/;
// Using regexp for a separator
document.write(str.split(pattern));
Output:
['HTML', 'CSS', 'JavaScript', 'Java', 'C', 'C++']
Overall
The JavaScript String method split()
divides a string into a list of substrings and returns them as an array.