split() JavaScript String Method – How to Split a String
Whenever you use split() on a string, the method does the following:
- It splits (divides) the string into substrings.
- It puts the substrings into an array.
- It returns the newly created array—without changing the original string.
Syntax of the split()
Method
Here is split()
’s syntax:
The snippet above shows that split()
accepts two arguments: a separation-point and an array-limit.
Argument 1: separation-point
A separation-point
is the first argument accepted by the split()
method. It is an optional argument that specifies the exact position where you want to split the string.
Example 1: Split string at whitespaces
The snippet above told the computer to split the calling string at each whitespace character.
Example 2: Split string at each letter o
Example 3: Split string at each digit character
Example 4: Split string at each hit
pattern
Example 5: Split string after each character
Argument 2: array-limit
An array-limit
is the second argument accepted by the split()
method. It is an optional argument indicating the limit of items the computer should put in the new array.
In other words, once the number of items in the new array equals the array-limit
, the computer will ignore the rest of the calling string’s characters.
Example 1: Split string at whitespaces but limit the returned array to one item only
Example 2: Split string at whitespaces but limit the returned array to two items
Example 3: Split string at whitespaces but limit the returned array to zero items
Example 4: Split string at each letter o
but limit the returned array to two items
Important Stuff to Know about split()
’s First Argument
When the separation-point
argument is an empty string (""
), the computer will use UTF-16 code units to split the calling string—not user-perceived characters (grapheme cluster).
Therefore, using an empty string as a separation point argument will destroy surrogate pairs and cause bugs in your application.
For instance, let’s use a surrogate character (💟) in a split statement:
You can see that split()
divided the calling string into four substrings—not three.
split()
returned an array of four substrings because the heart decoration character (💟) is a surrogate formed by a combination of the "\ud83d"
and "\udc9f"
code points.
In other words, split()
use UTF-16 code points to divide a string into an array of substrings—which can cause bugs that are difficult to spot.
A better alternative is to use the spread operator to split a string into a list of individual characters.
Here’s an example:
You can see that the spread syntax split the string correctly.