JavaScript split(): How to Use It and Avoid Pitfalls

How-to basics · Updated November 22, 2026

In JavaScript, use the string method split() to divide a string into an array, using a separator such as a comma, space, or regular expression. For example, 'red,green,blue'.split(',') returns ['red', 'green', 'blue']; the original string is not changed.

What split() does

split() is a method available on JavaScript strings. It scans a string for a separator and returns an array containing the portions between matches. The separator itself is normally left out of the returned array. The method is useful when a value that arrives as one string needs to be handled as separate pieces: a list of tags, a path, a line of text, or a simple delimited value.

The method does not modify the input. Strings are immutable in JavaScript, so the result is a new array; the original string remains available and unchanged. The array elements are strings, even when they contain digits. If you need numbers, convert the pieces explicitly rather than assuming that splitting performs a type conversion.

  • 'one,two'.split(',') produces ['one', 'two'].
  • 'one two'.split(' ') produces ['one', 'two'].
  • 'one,two'.split(';') produces ['one,two'], because the separator is not present.

Choose a string or regular-expression separator

The first argument is the separator. It can be a string or a regular expression. A string separator is a good choice when the boundary is known exactly, such as a comma in a basic list or a slash in a simple path. Matching is literal: a period in a string separator is a period, not the regular-expression wildcard.

Use a regular expression when the boundary can take several forms or should match a pattern. For instance, 'a,b; c'.split(/[,;]\s*/) returns ['a', 'b', 'c']. This expression treats a comma or semicolon as the delimiter and consumes any whitespace immediately after it. Regular-expression separators are particularly handy for text copied from inconsistent sources.

If the separator argument is omitted, or is undefined, the result is an array containing the whole string: 'hello'.split() returns ['hello']. That is different from passing an empty string. 'hello'.split('') splits the string into individual UTF-16 code units, an important distinction covered below.

Practical examples

For basic delimited text, call split() with the delimiter that marks each boundary. Then use the resulting array with ordinary array operations such as map(), filter(), or a loop. Here are common patterns:

  • Comma-separated simple values: 'tea,coffee,cocoa'.split(',') returns three elements.
  • Words separated by spaces: 'quick brown fox'.split(' ') returns ['quick', 'brown', 'fox'].
  • Lines with either newline convention: text.split(/\r?\n/) handles line feeds and Windows-style carriage-return-plus-line-feed endings.
  • Trimmed fields: ' north, south '.split(',').map(part => part.trim()) removes surrounding whitespace from each field.
  • Path segments: '/docs/setup'.split('/') returns an empty first element followed by 'docs' and 'setup', because the string begins with the separator.

For example, splitting and converting a simple list of numeric text can be done with '12,7,31'.split(',').map(Number), which returns [12, 7, 31]. This is suitable only when the input format is simple and the conversion behavior is acceptable. Real input may have blanks or invalid values, so validate the pieces before relying on them.

Using the limit argument

The optional second argument, limit, caps the number of elements in the returned array. It does not mean “split at most this many times and keep the remaining text as one final element.” Instead, it limits the result array, so anything after the allowed number of entries is omitted.

For example, 'a-b-c-d'.split('-', 2) returns ['a', 'b']; it does not return ['a', 'b-c-d']. A limit of 0 returns an empty array. The limit can be useful when only the first part matters, but it can also silently discard data if used without care. If you need to preserve the remainder after the first delimiter, split once and join the later pieces back together, or locate the delimiter with another string method.

JavaScript converts the limit to an unsigned 32-bit integer according to the method’s specification. Most everyday code should pass a non-negative integer directly. Avoid relying on unusual values such as negative numbers, fractions, or very large values to express application logic; make the intended count explicit instead.

Regular-expression captures and whitespace

A less obvious behavior is that capturing groups in a regular-expression separator are added to the result. For example, 'a=1;b=2'.split(/([;=]) /) would not be a good pattern for this exact text because there is no space after each delimiter. With the matching expression 'a=1;b=2'.split(/([;=])/), the result includes the delimiters: ['a', '=', '1', ';', 'b', '=', '2']. This can be useful when the matched punctuation must be retained, but it often surprises developers who only wanted to divide the text.

For splitting on one or more whitespace characters, use a regular expression such as text.split(/\s+/). Note the difference between that and text.split(' '): a literal space only matches one space at a time, so repeated spaces can create empty elements. The regular expression groups consecutive whitespace into one boundary.

There is a related empty-input detail: ''.split(/\s+/) returns [''], not an empty array. If a blank or whitespace-only string should represent no values, trim and check it first, for example const words = text.trim() ? text.trim().split(/\s+/) : [];. That explicit check makes the intended behavior clear.

Edge cases and common mistakes

Empty strings and leading or trailing separators can produce empty elements. 'a,,b'.split(',') returns ['a', '', 'b'], preserving the empty field between adjacent commas. Likewise, ',a,'.split(',') returns ['', 'a', '']. Those empty strings are meaningful when empty fields are allowed; filter them out only if the data rules say they should be ignored.

Using an empty-string separator does not split text by user-perceived characters in every case. JavaScript strings are sequences of UTF-16 code units, and some visible symbols, including many emoji, use more than one code unit. As a result, '😀'.split('') can produce two pieces that are halves of a surrogate pair rather than one intact emoji. For Unicode code points, Array.from('😀') is a better fit for many tasks. For full user-perceived grapheme clusters, such as a base letter combined with an accent, use Intl.Segmenter where supported and appropriate.

Another common mistake is treating split() as a complete parser. A comma-separated string can contain quoted fields, escaped commas, or newlines inside quoted values. A simple comma split cannot understand those rules: a value like '"New York, NY",Boston' will be divided at the comma inside the quotes too. For CSV files, use a CSV parser that implements the format rather than trying to cover its rules with a single split expression.

  • Check whether blank fields should be retained or removed.
  • Trim each result if surrounding whitespace is insignificant.
  • Confirm whether the separator is literal or needs pattern matching.
  • Validate and convert the result before treating text as numbers or trusted data.

How split() compares with related methods

split() is best when the desired output is an array of the pieces. If the goal is only to find or extract a portion, other string methods can be clearer. indexOf() locates a literal substring, slice() returns a part of a string by position, and match() or matchAll() can retrieve regular-expression matches.

For example, 'left:right'.split(':')[0] gets the text before a colon, but slice(0, value.indexOf(':')) may express that intention more directly once the missing-separator case is handled. Conversely, if a string has several fields and you need to process all of them, split() is usually straightforward. The right choice depends on whether the task is dividing, searching, extracting, or parsing structured data.

To combine an array back into a string, use join(). For example, ['red', 'green'].join(',') returns 'red,green'. Splitting and joining with the same simple delimiter can reconstruct many strings, but it is not guaranteed when empty fields, quoting rules, or transformations are involved.

Frequently Asked Questions

Does split() change the original string?
No. It returns a new array and leaves the original string unchanged. Assign the result if you need to keep or use the separated values.

How do I split a string by multiple spaces?
Use a regular expression such as text.split(/\s+/) to treat a run of whitespace as one separator. If the input can be blank, check the trimmed string first to avoid receiving [''].

Why does split(”) break an emoji?
An empty-string separator divides UTF-16 code units, while many emoji are represented by multiple code units. Use Array.from() for code-point iteration or Intl.Segmenter when you need grapheme-aware segmentation.

How do I split only once and keep the rest?
split(separator, 2) does not keep the remainder; it returns only the first two result elements. Find the first separator with indexOf() and use slice(), or split and rejoin the remaining pieces when that behavior suits the input.

Can split() parse CSV?
Not reliably when fields may be quoted, escaped, or contain delimiters. A plain split treats every matching comma as a boundary. Use a CSV parser for CSV data with those rules.

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.