JavaScript split(): How to Split Strings

How-to basics · Updated November 22, 2026

In JavaScript, call split() on a string to divide it at a separator and get an array of pieces: 'red,green,blue'.split(',') returns ['red', 'green', 'blue']. The separator can be a string or a regular expression, and an optional limit controls how many array entries are returned.

What JavaScript split() does

split() is a method of JavaScript strings. It looks for occurrences of the separator, removes those matches from the output, and returns the remaining portions as elements of a new array. It does not change the original string: strings are immutable in JavaScript, so you can still use the original value after splitting it.

This is useful whenever one string contains several values divided by a known marker, such as commas, spaces, line breaks, or a custom character. For instance, splitting a simple list into an array lets you loop over its items, sort them, or pass them to code that expects an array. The method only divides the text; it does not automatically trim spaces, convert numbers, or validate the resulting pieces.

Syntax and basic examples

The method has two optional parameters:

string.split(separator, limit)

  • separator is the string or regular expression that marks where to divide. If omitted, the entire string is returned as one array element.
  • limit is a maximum number of elements to include in the returned array. If it is zero, the result is an empty array.

For example, given const colors = 'red,green,blue';, colors.split(',') produces ['red', 'green', 'blue']. A multi-character separator works too: 'north--south--east'.split('--') produces ['north', 'south', 'east']. The separator must match exactly when it is a string, including spaces and punctuation.

When the separator is not present, splitting does not invent extra pieces. 'hello'.split(',') returns ['hello']. When the separator argument is left out, 'hello'.split() also returns ['hello']. That differs from passing an empty string, which has special behavior described below.

Choosing a string separator

Use a string separator when the text has a known, literal boundary. For example, '2026-11-03'.split('-') returns ['2026', '11', '03']. This is easy to read and avoids interpreting punctuation as regular-expression syntax. It is also appropriate for multi-character markers, such as 'key::value'.split('::').

Adjacent separators create empty strings between them, and separators at the start or end can create empty strings at the corresponding edge. For example, 'a,,b,'.split(',') returns ['a', '', 'b', '']. Those empty entries represent real empty fields in the input; they are not automatically discarded. Whether to keep or remove them depends on what the data means.

For text separated by whitespace of varying width, a regular expression is often more useful than a literal space. 'one two\tthree'.split(/\s+/) returns ['one', 'two', 'three'], because \s+ matches one or more whitespace characters. If the text may begin or end with whitespace, the resulting array can contain an empty first or last entry. Trim first when that is appropriate: text.trim().split(/\s+/). For input that might be empty or whitespace-only, check it before splitting if you want an empty array rather than an array containing an empty string.

Using regular expressions as separators

A regular-expression separator can match several possible delimiters or a variable amount of text. For example, 'apples, pears; plums'.split(/[,;]\s*/) returns ['apples', 'pears', 'plums']. The expression matches either a comma or semicolon, followed by optional whitespace. This is handy when input uses more than one separator style.

Regular-expression metacharacters have special meanings. A dot in a regular expression matches a character rather than a literal period, so use an escaped dot when the period itself is the separator: 'a.b.c'.split(/\./) returns ['a', 'b', 'c']. If a regular expression is unfamiliar, a string separator is usually clearer for a fixed literal marker.

There is an important detail with capturing parentheses. Captured matches are included in the result. For example, 'a,b;c'.split(/([,;])/) returns ['a', ',', 'b', ';', 'c']; the delimiters are retained as array elements because the pattern captures them. Use a non-capturing group, written (?:...), when grouping is needed but the matched delimiter should not appear in the output.

What the limit parameter changes

The second argument caps the number of entries in the result; it does not mean “split at this many separators and then keep the rest together.” For example, 'a,b,c,d'.split(',', 2) returns ['a', 'b']. The remaining text is not appended as a final combined entry. A limit can be useful when a program only needs an initial portion of the split result, but it is not a substitute for parsing the remainder.

With a regular expression that has capturing groups, captured pieces also occupy result positions, so they count toward the limit. If you want a predictable number of data fields, avoid capturing the separator unless you intend to keep it. In ordinary code, omitting the limit is clearest when every part is needed.

Empty strings, characters, and other edge cases

Splitting an empty string depends on the separator. ''.split(',') returns [''], because there is no comma and the original empty string remains the one piece. In contrast, ''.split('') returns []. This distinction can surprise code that assumes splitting always produces at least one item.

An empty-string separator divides a string into UTF-16 code units, JavaScript’s basic string storage units. That usually looks like one array entry per visible ordinary character, but it can break a character represented by a surrogate pair, such as many emoji, into two pieces that are not useful on their own. If you need Unicode code points, Array.from(text) is generally a better choice than text.split(''). Even code points are not always the same as user-perceived characters: a combined emoji or a letter plus a combining accent may consist of multiple code points. Where supported, Intl.Segmenter can segment text by grapheme cluster.

Trailing empty fields are another common source of bugs. A final separator is meaningful to split(): 'one,two,'.split(',') gives ['one', 'two', '']. Do not remove empty entries automatically if they might represent a missing value. Conversely, if the input format says empty fields should be ignored, filter them deliberately, for example with parts.filter(Boolean). Be aware that this removes every empty string, which may not be correct when field positions matter.

Parsing real input safely

For a simple line with a fixed separator, splitting is often all you need. Consider 'Ada|28|London'.split('|'), which gives three fields. You can then convert a numeric field with Number(fields[1]) and check that the expected number of fields exists. Splitting itself does not check that the input is valid, so code that processes external data should verify the result before relying on particular positions.

For line breaks, input may use either a line feed or a Windows-style carriage-return-plus-line-feed. A pattern such as /\r?\n/ handles those two common forms: text.split(/\r?\n/). If the source might also use lone carriage returns, use a pattern that accounts for all three common line-ending forms, such as /\r\n|[\n\r]/. The right choice depends on the source rather than on a universal rule.

A comma split is not a complete CSV parser. CSV fields may contain quoted commas, quote escaping, and line breaks inside quoted fields. For example, splitting 'Ada,"London, UK"' at every comma breaks the second field into two pieces even though the comma belongs inside the quoted value. For actual CSV files, use a CSV parser that follows the file format instead of trying to handle quoting with a quick split expression. The same principle applies to structured formats such as JSON: use a parser designed for the format.

When processing user-entered text, decide explicitly what to do about extra whitespace, missing fields, and unexpected separators. A useful sequence is:

  1. Choose a delimiter that matches the documented input format.
  2. Split the string and inspect the number of resulting fields.
  3. Trim or convert individual fields only when the format calls for it.
  4. Reject or handle malformed input before using its values.

How split() compares with related methods

split() turns a string into an array, which is useful when the task is to work with separate pieces. indexOf() or includes() can be simpler if you only need to find out whether a delimiter occurs. slice() and substring() extract a portion of a string when you know its character positions, while replace() changes or removes matching text rather than returning a list of fields.

There is also an array method named join(), which goes in the opposite direction: it combines array elements into a string using a separator. For example, ['red', 'green'].join(', ') returns 'red, green'. Joining does not guarantee that the original string can be reconstructed unless you preserve the same separator and account for values that themselves contain it.

For character-by-character work, choose based on what “character” means in the task. split('') works in UTF-16 code units, Array.from() iterates code points, and grapheme segmentation is needed when the goal is user-visible text units. For delimited records, use split() only when the delimiter rules are genuinely simple.

Frequently Asked Questions

Does split() change the original string?

No. It returns a new array and leaves the original string unchanged. You can store that array in a variable, but assigning or changing array elements does not alter the source string.

How do I split a string by spaces in JavaScript?

For one literal space, use text.split(' '). To handle one or more kinds of whitespace and repeated spaces, use text.split(/\s+/), and consider trimming first if leading or trailing whitespace should not create empty entries.

Why does split() return an empty string at the end?

A separator at the end marks an empty final field. Thus 'a,b,'.split(',') returns ['a', 'b', '']. Keep that value if it represents missing data; filter it only when the input rules say it should be ignored.

How can I split a string into individual characters?

text.split('') divides into UTF-16 code units and may break some Unicode characters. Use Array.from(text) for code points, or grapheme-cluster segmentation when each user-perceived character must stay intact.

Can split() use more than one delimiter?

Yes. Pass a regular expression that matches the alternatives, such as text.split(/[,;|]/) for commas, semicolons, or vertical bars. If the delimiters are part of the desired output, capture them intentionally; captured matches are included in the returned array.

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.