JavaScript’s String.prototype.split() method divides a string into an array of smaller strings using a separator you provide. Use a string or regular expression as the separator, and optionally pass a limit to control how many array entries are returned.
What the split() method does
split() searches a string for a separator and returns the pieces between the matches. The original string is not changed; JavaScript strings are immutable, and the method creates an array containing the results. This makes split() useful when a value arrives as one string but your code needs to process its parts individually.
For example, with a comma-separated list in colors, colors.split(',') returns an array such as ['red', 'green', 'blue']. You can then access an item by index, loop over the array, or call array methods such as map() and filter().
The separator marks where to cut; it is not normally included in the resulting pieces. There is one important exception: if the separator is a regular expression with capturing groups, the captured text is included in the result. That behavior is useful in some parsing tasks, but can surprise you if you add parentheses to a regular expression without intending to capture.
Syntax and return value
The method’s basic syntax is string.split(separator, limit). Both arguments are optional. It always returns an array, including when the input does not contain the separator or when the limit is zero.
- separator: A string or regular expression that identifies each split point. If omitted, the method returns an array containing the original string as its only element.
- limit: An optional number that caps the number of entries in the returned array. A limit of zero produces an empty array.
For instance, 'one,two,three'.split(',') returns ['one', 'two', 'three']. By contrast, 'one,two,three'.split() returns ['one,two,three'], because no separator was supplied. Calling split(undefined) has the same practical result as omitting the argument.
The return value is an array even if it contains just one item. To turn an array back into a string with a chosen delimiter, use join(), for example parts.join(', '). Splitting and joining can be useful together, but they are not necessarily a lossless round trip: the original spacing and separator choices may not be preserved.
Choosing a string or regular-expression separator
A string separator is the clearest choice when the delimiter is a known, exact sequence of characters. Use split(',') for commas, split('|') for vertical bars, or split(' - ') when the spaces around a hyphen are part of the delimiter. Matching is literal, so a period passed as a string means an actual period, not a regular-expression wildcard.
A regular expression is useful when more than one character or pattern should count as a delimiter. For example, 'red, green; blue'.split(/[,;]/) splits at commas and semicolons. To treat one or more whitespace characters as a single delimiter, use 'red green\tblue'.split(/\s+/). Here \s matches whitespace and the plus sign means one or more occurrences, so a run of spaces does not create several empty entries.
Regular expressions have their own syntax rules. Characters such as a period, question mark, or vertical bar have special meanings in a regular expression. If you intend to match one of those literally, escape it where necessary; for example, 'a.b.c'.split(/\./) splits at periods. For a single fixed delimiter, a string is often easier to read and less error-prone.
Capturing parentheses affect the output. 'a,b'.split(/(,)/) returns ['a', ',', 'b'], because the captured comma is inserted into the array. If you need grouping but do not want the matched delimiter returned, use a non-capturing group, written as (?:...), or choose a pattern without a capturing group.
Using the limit argument
The optional limit sets the maximum number of array elements, not the maximum number of separator matches in a separate result. For example, 'north,south,east,west'.split(',', 2) returns ['north', 'south']. Once the result has reached the limit, the remaining text is not added as another item.
This argument can be handy when you only need the first few fields. It is not the same as splitting once and keeping the unparsed remainder: the remainder is discarded. If you need a first field plus all the remaining text, split and then rejoin the remaining array entries, or locate the first delimiter with a method such as indexOf() and slice the original string.
A limit of 0 returns []. In normal application code, pass a nonnegative integer so the result is easy to reason about; fractional, negative, or unusually large values are subject to JavaScript’s numeric conversion rules and are best avoided unless you deliberately need those semantics.
Practical examples
Here are common patterns, with the result shown for each:
- Split a comma-separated value:
'Ada,Grace,Linus'.split(',')returns['Ada', 'Grace', 'Linus']. - Split on repeated whitespace:
' one two '.trim().split(/\s+/)returns['one', 'two']. Trimming first avoids empty entries at the beginning and end. - Split a path on forward slashes:
'docs/api/index.html'.split('/')returns['docs', 'api', 'index.html']. - Split lines with either LF or CRLF endings:
text.split(/\r?\n/)handles the common line-ending styles used on Unix-like systems and Windows. - Keep only two fields:
'A|B|C'.split('|', 2)returns['A', 'B'];Cis omitted.
For line-oriented text that may also contain old-style carriage-return-only endings, a broader expression such as text.split(/\r\n?|\n/) accounts for CRLF, CR, and LF. Decide how to handle a final line ending: splitting a string that ends with a delimiter can produce a final empty string, which may or may not represent a meaningful blank line in your application.
Empty strings, missing matches, and empty entries
Several edge cases are worth knowing before relying on the output. If the separator is not found, the result is an array containing the whole input. Thus 'hello'.split(',') produces ['hello'], not an empty array. If the input is an empty string and the separator is a nonempty string, such as ''.split(','), the result is [''].
Consecutive delimiters and delimiters at the edges can create empty entries. For example, 'a,,b,'.split(',') returns ['a', '', 'b', '']. The empty item between the commas represents the missing value between those delimiters, and the last empty item comes from the trailing comma. Do not remove these entries automatically if their positions carry meaning, such as in a delimited record with blank fields.
If empty pieces are unwanted, you can filter them out after splitting: value.split(',').filter(Boolean). That removes empty strings, but it also removes any other false-like values if the array contains them. With a plain split result, the entries are strings, so the main effect is removing empty strings. If whitespace-only pieces should also count as empty, trim each piece before filtering, for example with value.split(',').map(part => part.trim()).filter(Boolean).
Common pitfalls and data-format limits
A frequent mistake is assuming that splitting on a space handles every kind of whitespace cleanly. split(' ') matches one ordinary space at a time; repeated spaces create empty entries, and tabs or line breaks are not matched. Use a whitespace regular expression when the input can contain varying whitespace, and trim first if leading or trailing whitespace should be ignored.
Another misconception is that split(',') is a complete CSV parser. It is not. Real CSV data can contain quoted fields with commas inside them, escaped quotation marks, and line breaks inside quoted values. A simple split would incorrectly break a value such as "New York, NY" into two pieces. For CSV files, use a CSV parser that follows the format’s quoting rules rather than treating commas as unconditional separators.
Similarly, splitting a URL on a question mark or a path on a slash may be adequate for a simple, controlled string, but structured formats have encoding and edge cases. For URLs, the URL and URLSearchParams APIs are usually safer for accessing components and query parameters. Choose the parser that understands the data format when correctness matters.
Unicode and splitting into characters
Passing an empty string as the separator, as in 'cat'.split(''), returns individual UTF-16 code units: ['c', 'a', 't']. For basic English text this often looks like splitting into characters, but JavaScript strings use UTF-16, and some visible symbols are represented by more than one code unit. An emoji can therefore be broken into pieces that are not independently useful characters.
If you need to iterate over Unicode code points, use Array.from(text) or the spread syntax [...text]. These handle surrogate pairs as one code point, but a user-perceived character can still consist of several code points, such as a letter plus a combining accent or a multi-part emoji. For grapheme clusters, which more closely correspond to visible characters, use Intl.Segmenter with grapheme granularity in environments that support it. The right choice depends on whether you mean code units, code points, or user-perceived characters.
When to use split() and when to use another method
Use split() when you want all pieces of a string as an array and you know what separates them. It is concise for simple lists, paths, and predictable text records. Other methods are better when you need a different result or the input has structure:
indexOf()andslice()can isolate a portion of a string without creating an array of every field.match()ormatchAll()can be more appropriate when you want text matching a pattern rather than the pieces between delimiters.replace()is for transforming or removing matched text, not for returning separated fields.- A format-specific parser is safer for CSV, URLs, JSON, and other data with rules beyond a simple separator.
Performance is rarely the first concern for ordinary strings. Readability and correct handling of the input format matter more. If splitting very large data repeatedly becomes a measured bottleneck, consider whether the full array is needed or whether the input can be processed incrementally. Do not choose a more complicated approach based only on a guess about speed.
Frequently Asked Questions
Does split() change the original string?
No. Strings are immutable in JavaScript, and split() returns a new array. The original string remains unchanged.
What does split() return if the separator is missing?
It returns a one-element array containing the complete original string. For example, 'abc'.split(',') returns ['abc'].
How do I split a string by multiple delimiters?
Use a regular expression with the delimiter choices, such as value.split(/[;,]/) to split at commas or semicolons. Remember that capturing groups are included in the returned array.
How do I split a string and remove extra spaces?
For a whitespace-separated value, trim the ends and split on one or more whitespace characters: value.trim().split(/\s+/). If the input may be empty, handle that case separately because trimming an empty string and splitting it still produces an array containing an empty string.
Why does splitting on an empty string break an emoji?split('') separates UTF-16 code units, not necessarily complete Unicode characters. Use Array.from() for code points or Intl.Segmenter when you need user-perceived grapheme clusters.
Related
- Snowflake SPLIT to Array: Syntax, Examples, and Tips
- JavaScript String Length: How the length Property Works
- Access Split Forms: How They Work and When to Use One
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Budget Spreadsheet Template for Google Sheets: SetupYes—a budget spreadsheet template for Google Sheets is available through the Sheets template gallery when a suitable template…
- DVD Labels in Microsoft Word: Setup and Printing GuideYes. You can create DVD labels in Microsoft Word by opening a matching label template or laying out…
- Media Excel Shortcuts for Images, Links, and ObjectsExcel has no single keyboard shortcut for all media. In Microsoft 365 for Windows, use Ctrl+V to paste…
- Excel Consolidate Multiple Sheets Into One: 4 MethodsYes. In Excel for Microsoft 365 on Windows, you can combine sheets by appending their rows with Power…
- Excel Goal Seek for Multiple Cells: How Solver WorksExcel’s Goal Seek can change only one input cell at a time. To make Excel adjust multiple cells…
- Excel Data Model: Can You Turn It Off?Excel has no single switch that turns off a workbook’s Data Model. To stop a Power Query query…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.