String.prototype.split()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The split() method of String values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
Try it
const str = "The quick brown fox jumps over the lazy dog.";
const words = str.split(" ");
console.log(words[3]);
// Expected output: "fox"
const chars = str.split("");
console.log(chars[8]);
// Expected output: "k"
const strCopy = str.split();
console.log(strCopy);
// Expected output: Array ["The quick brown fox jumps over the lazy dog."]
Syntax
split(separator)
split(separator, limit)
Parameters
separator-
The pattern describing where each split should occur. Can be
undefined, a string, or an object with aSymbol.splitmethod — the typical example being a regular expression. Omittingseparatoror passingundefinedcausessplit()to return an array with the calling string as a single element. All values that are notundefinedor objects with a[Symbol.split]()method are coerced to strings. limitOptional-
A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified
separator, but stops whenlimitentries have been placed in the array. Any leftover text is not included in the array at all.- The array may contain fewer entries than
limitif the end of the string is reached before the limit is reached. - If
limitis0,[]is returned.
- The array may contain fewer entries than
Return value
If separator is a string, an Array of strings is returned, split at each point where the separator occurs in the given string.
If separator is a regex, the returned Array also contains the captured groups for each separator match; see below for details. The capturing groups may be unmatched, in which case they are undefined in the array.