.split()
Published Jun 23, 2021Updated Jul 27, 2022
Contribute to Docs
The .split()
method returns a new array of substrings based on a given string.
Syntax
string.split(separator, limit);
The separator
(optional) describes the pattern where each split should occur. It may be one of the following:
- A string of one or more characters.
- A regular expression.
If a separator
is not provided, the returned array will contain the entire string
as its lone element.
The limit
(also optional) determines the number of substring elements included in the returned array.
Example
The following example splits a string into an array of names:
const stringOfNames = 'Dominic, Shelly, Luka, Devin';console.log('No limit:', stringOfNames.split(', '));console.log('Limited to 3 elements:', stringOfNames.split(', ', 3));
This will log the following output:
No limit: [ 'Dominic', 'Shelly', 'Luka', 'Devin' ]Limited to 3 elements: [ 'Dominic', 'Shelly', 'Luka' ]
Codebyte Example
The following example showcases the .split()
in two ways:
- Not including a
separator
returns anarrayOfNames
with the entirestringOfNames
as the sole element. - The
arrayOfNames
is reassigned with aseparator
and then traversed with.split()
being invoked on each name.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.