JavaScript split() Syntax, Examples, and Pitfalls

How-to basics · Updated November 22, 2026

In JavaScript, use string.split(separator, limit) to divide a string into an array of pieces wherever the separator occurs. For example, "red,green,blue".split(",") returns ["red", "green", "blue"]; the separator can be a string or a regular expression, and the optional limit caps how many array items are returned.

Basic split() syntax

split() is a method of JavaScript strings. Call it on the string you want to divide, then provide the value that marks each boundary:

const parts = "one two three".split(" ");
console.log(parts); // ["one", "two", "three"]

The method returns a new array. It does not change the original string, because strings are immutable in JavaScript. The usual form has two arguments:

  • separator is the string or regular expression that identifies where to divide the input.
  • limit is optional and sets the maximum number of items in the returned array.

The separator is a delimiter, not a value to search for and remove afterward. When a string separator is used, JavaScript looks for that exact sequence of characters. For example, "a--b--c".split("--") returns ["a", "b", "c"]. It does not interpret the hyphens as a pattern.

What split() returns and how it works

JavaScript scans the input for separator matches and places the text between those matches into an array. The separator itself is normally left out of the result. If the separator appears more than once, each occurrence creates another boundary. If it does not appear, the returned array contains the original string as its only element.

"hello".split(","); // ["hello"]
"a,b,c".split(","); // ["a", "b", "c"]
"a,,c".split(","); // ["a", "", "c"]

That empty string in the final example is meaningful: it represents the empty field between two adjacent commas. Likewise, a separator at the start or end of a string can produce an empty first or last item. This is useful when empty fields are part of the data, but it can also surprise code that assumes every array item contains text.

If you call split() without an argument—or pass undefined as the separator—the result is an array containing the whole string. That differs from passing an empty string. An empty string separator asks JavaScript to divide the input between its UTF-16 code units, which is a special case discussed below.

Common string-splitting examples

For simple, consistently formatted text, a literal separator is usually the clearest choice. These examples show patterns commonly used to turn text into arrays:

const words = "learn JavaScript today".split(" ");
// ["learn", "JavaScript", "today"]

const fields = "Ada,Lovelace,1843".split(",");
// ["Ada", "Lovelace", "1843"]

const pathParts = "/products/books/".split("/");
// ["", "products", "books", ""]

const lines = "first\nsecond\nthird".split("\n");
// ["first", "second", "third"]

Notice that splitting a path on "/" retains empty pieces around the leading and trailing slash. If those pieces are not useful, you can filter them explicitly:

const pathParts = "/products/books/".split("/").filter(Boolean);
// ["products", "books"]

filter(Boolean) removes all falsy array values, including empty strings. Use it only when removing empty fields is actually appropriate; in a data format where an empty field has meaning, filtering would discard information.

For line breaks from different operating systems, a regular expression can handle either a line feed or a carriage return followed by a line feed: text.split(/\r?\n/). This is often more robust than assuming every input uses just one newline convention.

Using regular expressions as separators

A regular expression lets the separator describe a pattern rather than one exact string. For instance, to split on one or more whitespace characters—spaces, tabs, or line breaks—use /\s+/:

const words = "  red\tgreen\nblue  ".trim().split(/\s+/);
// ["red", "green", "blue"]

The trim() call removes whitespace at the ends before splitting. Without it, the leading whitespace can create an empty first item, and trailing whitespace can create an empty last item. Whether to trim depends on whether those boundary spaces should be ignored or preserved.

Regular expressions can also describe several possible delimiters. For example, "a,b;c".split(/[,;]/) returns ["a", "b", "c"], splitting on either a comma or a semicolon. Flags can affect matching; for example, a case-insensitive regular expression can match separators regardless of letter case.

One notable behavior is that capturing groups in a separator regular expression are included in the output array. Thus "a1b2c".split(/(\d)/) returns ["a", "1", "b", "2", "c"]. If you want the delimiter to match but not appear in the result, use a non-capturing group, written as (?:...), where grouping is needed. This detail matters when an otherwise harmless pair of parentheses changes the shape of the returned array.

The limit argument and empty strings

The optional second argument limits the number of array items, not the number of matches to search for. With "a,b,c".split(",", 2), the result is ["a", "b"]. Once the result reaches the limit, later text is not added. A limit of 0 returns an empty array. In ordinary application code, pass a non-negative integer so the intent is clear.

Empty input and an empty separator have distinct results:

"".split(","); // [""]
"".split("");  // []
"abc".split(""); // ["a", "b", "c"]

When the input is empty and the separator is non-empty, the result contains one empty string because there is no separator to divide the input. When the separator is the empty string, JavaScript splits a non-empty string between UTF-16 code units. This can produce what looks like individual characters for ordinary English text, but it is not a reliable way to split every Unicode character.

Common mistakes and edge cases

  • Expecting a string separator to be a pattern. split(".") looks for a literal period. To split on a regular-expression pattern, use a regular expression such as split(/\./); the backslash makes the period literal within the pattern.
  • Forgetting repeated delimiters. Splitting "one, two" on a comma leaves the leading space in the second item. Use split(/,\s*/) when commas and any following whitespace should form one delimiter.
  • Assuming empty fields disappear. Consecutive separators can create empty strings. Check the data before filtering them out.
  • Using split() as a complete CSV parser. A comma-separated file may contain quoted fields with commas inside them, escaped quotation marks, and line breaks within quoted values. A simple split(",") cannot correctly parse those rules. Use a CSV parser for real CSV data.
  • Splitting user-perceived characters with an empty string. Some visible characters consist of multiple Unicode code points, such as an emoji with a skin-tone modifier or a letter plus a combining accent. Splitting into UTF-16 code units can break surrogate pairs and does not preserve grapheme clusters.

For Unicode-aware work, Array.from(text) iterates by code point, so it avoids splitting a surrogate pair, but it can still separate a combining mark from its base letter. For user-visible grapheme clusters, Intl.Segmenter with grapheme granularity is the more suitable built-in option in environments that support it.

When to use split() and what to use instead

Use split() when the input is a string and the delimiter rules are simple and known. It is particularly convenient for turning a short list into an array, parsing a basic delimited value, or separating text into lines or tokens. The resulting array can then be processed with methods such as map(), filter(), or join().

Choose a different tool when the input structure is more complex than delimiter boundaries:

  • For CSV or other quoted formats: use a parser that understands quoting and escaping instead of splitting on commas.
  • For a fixed number of pieces: split and then validate the array length, or use targeted string methods such as indexOf() and slice() when their behavior better expresses the task.
  • For matching and extracting structured text: a regular expression with match() or matchAll() may make the extraction rules clearer.
  • For Unicode characters: use code-point or grapheme-aware iteration rather than assuming an empty separator returns user-perceived characters.

There is no need to convert a string into an array just to look for one substring; includes() is often simpler for that job. Similarly, if the goal is to replace delimiters rather than keep the intervening pieces, replace() may be a better fit. Pick the operation that reflects the intended result, then check how it handles whitespace, empty values, and malformed input.

Frequently Asked Questions

What does split() do in JavaScript?

It divides a string wherever a supplied string or regular-expression separator matches and returns the pieces in a new array. The separator is normally not included, except that captured groups in a regular-expression separator are included.

How do I split a string by spaces?

Use text.split(" ") for literal single spaces. To split on runs of spaces, tabs, or other whitespace, use text.split(/\s+/). If leading or trailing whitespace should not create empty items, trim the text first.

How do I split a string into characters?

text.split("") separates UTF-16 code units, not necessarily complete Unicode characters. Array.from(text) handles Unicode code points more safely, while Intl.Segmenter can divide text into grapheme clusters for user-visible character handling.

Does split() change the original string?

No. Strings are immutable, and split() returns a new array without modifying the source string. You can store that array, transform it, or join it back into a string separately.

How can I limit the number of split results?

Pass a second argument, such as text.split(",", 3), to return at most three array items. A limit of zero returns an empty array. Remember that the limit counts output items, not delimiters.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.