String.prototype.split
Splits a string into an array by a separator.
Available since: ES3
Syntax
str.split(separator, limit)Parameters
| Parameter | Type | Description |
|---|---|---|
| separator | string | The separator to split by. |
| limit | number | Optional. The maximum number of elements in the result. |
Return value
ArrayAn array of the string's parts.
Examples
Splitting by a comma:
console.log('red,green,blue'.split(','));Output:
[
"red",
"green",
"blue"
]An empty separator splits the string into characters:
console.log('code'.split('').join(' - '));Output:
c - o - d - eNotes
join() does the reverse. Strings with emoji are split into characters more reliably with [...str].
See also
- Array.prototype.join — Joins array elements into a string.
- String.prototype.slice — Returns part of a string.
- RegExp — A regular expression — a pattern for finding and replacing text.
- Array.from — Creates an array from a string, Set, Map or another iterable.
Related recipes
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.