.split()

BrandonDusch's avatar
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:

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:

  1. Not including a separator returns an arrayOfNames with the entire stringOfNames as the sole element.
  2. The arrayOfNames is reassigned with a separator and then traversed with .split() being invoked on each name.
Code
Output
Loading...

All contributors

Contribute to Docs

Learn JavaScript on Codecademy