split()

ES3+

Divides a string into an ordered list of substrings by searching for a separator pattern, and returns them as a new array. The separator can be a plain string or a regular expression, and an optional limit caps how many pieces are returned. The original string is never modified, because JavaScript strings are immutable.

Syntax

string.split(separator, limit)

Parameters

separator string | RegExp

The pattern describing where each split should occur

limit number optional

Limit on the number of substrings to return

Return Value

Array

An Array of strings split at each point where the separator occurs

Examples

JavaScript
const str = 'Hello World';
console.log(str.split(' '));
console.log(str.split(''));
Output:
// ['Hello', 'World'] ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

📌 When to Use

Use split() whenever you need to turn one string into many: parsing a CSV line into fields, breaking a sentence into words, reading key-value pairs out of a query string, or converting a multi-line file into an array of lines with split(String.fromCharCode(10)). It is the natural inverse of Array.prototype.join(), and the two are frequently paired: split a string, transform the pieces with map() or filter(), then join them back together. Reach for a string separator when the delimiter is fixed and literal, such as a comma or a slash. Reach for a regular expression separator when the delimiter varies, for example one-or-more whitespace characters, or a comma optionally followed by spaces. The limit parameter is useful when you only care about the first few fields of a long record, such as pulling the method and path out of an HTTP log line. Avoid split() when you only need to test for the presence of a substring (use includes()) or extract a single piece by position (use slice() with indexOf()), because building a whole array for one answer is wasted work. For splitting user-visible text into characters, prefer the spread operator or Intl.Segmenter over split with an empty string, which breaks emoji and other astral symbols.

⚠️ Common Mistakes

Splitting into characters with an empty-string separator: split() with '' divides the string at every UTF-16 code unit, not every visible character. An emoji or any code point above U+FFFF is stored as a surrogate pair, so it gets torn into two useless halves. Use the spread operator, Array.from(), or Intl.Segmenter to split by code points or grapheme clusters instead.

Assuming a missing separator returns an empty array: when the separator never occurs in the string, split() returns a one-element array containing the whole original string. Code that blindly reads result[1] will get undefined, so check the resulting length before indexing into it.

Forgetting that a regular expression separator with capturing groups changes the output: any text captured by parentheses in the separator is spliced into the result array between the fields. Use non-capturing groups (?:...) if you only meant to group alternatives, or you will find delimiter fragments mixed into your data.

Ignoring empty strings in the result: 'a,,b'.split(',') yields three elements, one of them empty, and a trailing delimiter produces a trailing empty string. Splitting an empty string with a non-empty separator also returns [''], not []. Filter out empty entries explicitly when they are not meaningful.

Misreading the limit parameter: limit truncates the output array, it does not change where splitting stops semantically or glue the remainder onto the last element the way some other languages do. 'a,b,c'.split(',', 2) returns ['a', 'b'] and the 'c' is simply discarded, not appended as 'b,c'.

✅ Best Practices

Pass the limit argument when you only need the first few fields; the engine can stop scanning and allocating early, which matters on long log lines or large CSV rows.

Use a regular expression separator like one built from /,\s*/ style patterns to absorb inconsistent whitespace around delimiters in user input, instead of splitting on a bare comma and trimming every element afterwards.

Chain filter(Boolean) or a length check after splitting when double delimiters or trailing separators could produce empty strings that would corrupt later processing.

Prefer non-capturing groups (?:...) inside regular expression separators so delimiter text does not leak into the result array as extra elements.

For real CSV data that may contain quoted fields with embedded commas, use a proper CSV parser rather than split(','); the naive split approach silently breaks on the first quoted field.

When you need both the pieces and the delimiters that separated them, use matchAll() or split with a capturing group deliberately, and document that choice, rather than reconstructing positions with repeated indexOf calls.

⚡ Performance Notes

split() allocates a new array plus one new string per element, so its cost is proportional to both the input length and the number of pieces produced. For a one-off parse this is negligible, but splitting megabyte-scale strings inside a hot loop creates significant garbage-collection pressure. The limit parameter is the cheapest optimization available: engines stop scanning once the limit is reached, so extracting two fields from a thousand-field record does a fraction of the work. String separators are faster than regular expression separators because no regex machinery is involved; if you do use a regex in a loop, create it once outside the loop so it is compiled a single time. When you only need to locate one piece, indexOf() plus slice() avoids materializing the whole array and is usually several times cheaper.

🌍 Real World Example

Parsing CSV Data

Two everyday parsing jobs built on split(). parseCSVRow() breaks a comma-separated record into cells, trims stray whitespace from each one with map(), and drops empty cells with filter(), producing a clean array of column values. parseQueryString() splits a URL query on the ampersand character to get key-value pairs, then splits each pair on the equals sign with a limit of 2 so values containing '=' are not mangled, decodes them, and accumulates everything into a plain object with reduce(). Both functions show the typical pattern: split first, then clean and reshape the pieces with array methods.

// Parse CSV row into columns
function parseCSVRow(row) {
  // Split by comma and trim whitespace
  return row.split(',')
    .map(cell => cell.trim())
    .filter(cell => cell.length > 0);
}

const data = 'John, Doe, john@example.com, Developer';
const columns = parseCSVRow(data);
console.log(columns);
// Output: ['John', 'Doe', 'john@example.com', 'Developer']

// Parse URL query parameters
function parseQueryString(query) {
  return query.split('&').reduce((params, pair) => {
    const [key, value] = pair.split('=', 2);
    params[key] = decodeURIComponent(value || '');
    return params;
  }, {});
}

const query = 'name=John&age=30&city=Seoul';
console.log(parseQueryString(query));
// Output: { name: 'John', age: '30', city: 'Seoul' }

Related Methods