String.prototype.split()

Divides a string into an array of substrings using a separator string or regular expression.

Signature
split(separator)
split(separator, limit)
  • Added in JavaScript ES1

Parameters

ParameterTypeDescription
$separatoroptionalstring | RegExp | { [Symbol.split](): any }The pattern describing where each split should occur. Omitting it or passing undefined returns an array holding the whole string as a single element. Values that are neither undefined nor objects with a [Symbol.split]() method are coerced to strings.
$limitoptionalnumberA non-negative integer capping how many substrings end up in the array. Splitting stops once limit entries are collected and any leftover text is discarded. A limit of 0 returns an empty array.

Return value

Array<string>An array of strings, split at each point where the separator occurs. If the separator is a regex, the array also contains the captured groups for each separator match; unmatched groups appear as undefined.

split() is the workhorse for turning flat text into structured data: CSV rows, path segments, query parameters, lines of a file.

Things that surprise people

  • Empty separator. split("") splits into UTF-16 code units, not characters. Any emoji or astral-plane character comes back as two broken halves. Use [...str] or Array.from(str), which iterate by code point.
  • No separator at all. "abc".split() returns ["abc"], not ["a", "b", "c"].
  • Consecutive separators produce empty strings. "a,,b".split(",") is ["a", "", "b"]. Filter them out or split on a regex such as /,+/.
  • limit truncates, it does not group. "a,b,c".split(",", 2) is ["a", "b"] — the "c" is thrown away, unlike the equivalent in some other languages.
  • Capture groups are kept. If the separator regex has capturing groups, their matches are interleaved into the result, which is handy for splitting while retaining the delimiters.

For real CSV with quoted fields, do not use split(",") — a quoted comma will break it. Use a parser.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Turn a comma-separated settings string into an array
  • Split a multi-line log into individual lines on /\r?\n/
  • Break a URL path into its segments
  • Split a full name into first and last on the first space only

Frequently asked questions

How do I split a string into individual characters in JavaScript?

Use [...str] or Array.from(str) rather than str.split(""). split("") divides the string by UTF-16 code unit, which tears emoji and other astral-plane characters into two unusable halves, while the spread syntax iterates by code point.

Why does split return empty strings in the array?

Because two adjacent separators have nothing between them, and split() faithfully reports that empty gap as an empty string. Split on a repeating regex such as /,+/ or filter the result with .filter(Boolean) if you want them gone.

What does the limit argument in split do?

It caps how many substrings end up in the returned array and discards the rest of the string entirely. "a,b,c".split(",", 2) returns ["a", "b"] — the "c" is not appended to the last element.

More examples

Splitting characters without breaking emoji

split("") reports length 4 because the emoji occupies two UTF-16 code units and each half is emitted separately. Spreading the string uses the string iterator, which walks code points, so the emoji stays intact and the length is 3.

Example · javascript
const s = "😀ab";

console.log(s.split(""));      // 3+ broken units
console.log(s.split("").length); // 4

console.log([...s]);           // ["😀","a","b"]
console.log([...s].length);    // 3
console.log(Array.from(s).length); // 3

Keeping the delimiters with capture groups

The first call loses the operators entirely. The second returns ["3","+","4","*","2","-","1"] because a capturing separator regex inserts each captured delimiter into the output, giving 7 tokens.

Example · javascript
const expr = "3+4*2-1";

// Without a group the operators are discarded
console.log(expr.split(/[+*-]/));

// With a capturing group they are interleaved
console.log(expr.split(/([+*-])/));

// Useful for tokenising
const tokens = expr.split(/([+*-])/).filter(Boolean);
console.log(tokens.length);

Splitting on only the first occurrence

The limited split drops everything after the second field, so the token's own colon is lost. The indexOf approach keeps the full value "Bearer abc:def", which is what header parsing actually needs.

Example · javascript
const header = "Authorization: Bearer abc:def";

// limit throws away the tail — usually not what you want
console.log(header.split(":", 2)); // ["Authorization", " Bearer abc"]

// Split once, keep the remainder
const i = header.indexOf(":");
console.log([header.slice(0, i), header.slice(i + 1).trim()]); // ["Authorization", "Bearer abc:def"]

Discussion

  • Be the first to comment on this lesson.