JavaScript Reference ยท String
String.prototype.split()
Reference for JavaScript String.prototype.split(): break a string into an array by a separator or regular expression, use a limit, and avoid common pitfalls.
The split() method divides a string into an ordered list of substrings and returns them as an array. You tell it where to cut with a separator, which can be a string or a regular expression. The separator itself is not part of the results.
It is the standard way to turn comma-separated values, words, lines or paths into arrays. The opposite operation is Array.prototype.join().
"a,b,c".split(","); // ["a", "b", "c"]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
string.split() string.split(separator) string.split(separator, limit)
| Name | Description |
|---|---|
separator |
A string or a regular expression (or an object with a Symbol.split method) that marks where to cut. If omitted or undefined, the result is an array with the whole string as its only element. |
limit |
The maximum number of items in the result. Extra parts are discarded, not joined to the last item. It is converted to an unsigned 32-bit integer; 0 returns an empty array. |
Return value: an array of strings.
Exceptions: none for ordinary input.
Usage notes
- An empty-string separator splits into UTF-16 code units, so characters outside the Basic Multilingual Plane, such as most emoji, are broken in two. Use
Array.from(str)or[...str]to split by code points. - Empty input:
"".split(",")gives[""](one empty string), but"".split("")gives[]. - Adjacent separators produce empty strings, and so do separators at the start or end:
",a,".split(",")is["", "a", ""]. - Capture groups in a regular expression separator are included in the result between the pieces. Use non-capturing groups
(?:...)to avoid that. limittruncates the array; it does not stop the work early in a way you can rely on, and the rest of the string is simply dropped.- Splitting on whitespace:
split(/\s+/)collapses runs of whitespace, but leading whitespace still gives an empty first item. Calltrim()first. - Not a CSV parser. Quoted fields that contain separators are not handled.
- Original unchanged: strings are immutable and
split()returns a new array.
Browser support
String.prototype.split() is supported in every browser.