In JavaScript, String.prototype.split() divides a string at a separator and returns the resulting pieces in an array. Call it as text.split(separator, limit); the separator can be a string or a regular expression.
What the split() method does
split() is a method on strings. It scans the original string for occurrences of the separator, cuts at those boundaries, and returns the sections as array elements. It does not change the original string, so you can store the returned array, inspect it, or pass it to another operation.
A basic example splits a comma-delimited string:
const colors = 'red,green,blue'.split(',');
// ['red', 'green', 'blue']
The separator itself is normally removed from the results. In this example, the commas mark where to cut, but none of the array elements contains a comma. The returned array can be indexed or used with array methods such as map() and join().
Syntax and the separator
The method accepts two arguments: separator and an optional limit. The first determines where to divide the string. When it is a string, JavaScript looks for that exact sequence of characters. Matching is case-sensitive, and a multi-character separator is treated as one complete sequence.
const path = 'photos/2026/summer';
const parts = path.split('/');
// ['photos', '2026', 'summer']
const phrase = 'one--two--three';
const values = phrase.split('--');
// ['one', 'two', 'three']
A separator does not have to be one character. Conversely, split(' ') looks for a literal space character; it does not automatically match tabs, line breaks, or runs of whitespace. For flexible matching, use a regular expression, described below.
If you call split() without a separator, or pass undefined, the result is an array containing the whole string as its only element. This is different from passing an empty string. An explicit separator such as null is converted to a string for matching, so it is generally clearer to pass the separator you actually intend.
Splitting on whitespace and other patterns
A regular expression separator is useful when the boundary may vary. For example, /\s+/ matches one or more whitespace characters, so it can handle a single space, repeated spaces, tabs, and line breaks:
const words = ' JavaScript is\tuseful '.trim().split(/\s+/);
// ['JavaScript', 'is', 'useful']
Here, trim() removes whitespace at the beginning and end before the split. Without trimming, leading or trailing separators can produce empty strings at the corresponding edge. Whether to trim first depends on whether those empty fields carry meaning in your data.
Regular expressions can also separate on several punctuation marks. A character class such as /[,;]+/ treats any run of commas or semicolons as a boundary:
const items = 'tea,coffee; water'.split(/[,;]\s*/);
// ['tea', 'coffee', 'water']
The expression includes optional whitespace after the punctuation, which prevents spaces from remaining at the starts of later elements. Choose the pattern to match the format you actually accept; a permissive separator can conceal malformed input rather than validate it.
Using the limit argument
The optional second argument caps how many entries the returned array contains. For example, a limit of two returns no more than the first two pieces:
const fields = 'name,age,city'.split(',', 2);
// ['name', 'age']
A limit of zero returns an empty array. A positive limit does not mean that the original string is shortened or changed; it only restricts the result. This can be handy when you need an initial portion, but it is not a substitute for parsing a structured format. In particular, limiting a CSV-like split can leave the final element containing text that includes additional separators.
When using a regular expression with capturing parentheses, captured matches are also included in the result. Those captured values count toward the limit. For instance, splitting 'a,b,c' with /(,)/ yields alternating text and comma entries; a small limit may therefore stop sooner than expected. Use non-capturing parentheses, written (?:...), when grouping is needed but the separator text should not appear in the output.
Empty strings, repeated separators, and edge cases
Adjacent matches create empty strings between them, because there is a section of zero characters between each pair of separators. A separator at the beginning or end can also create an empty first or last element:
const values = 'a,,b,'.split(',');
// ['a', '', 'b', '']
Those empty elements are not automatically errors. They may represent blank fields in a simple delimited record. If your application wants to discard them, filter them deliberately, for example with values.filter(value => value !== ''). Avoid filtering blindly if an empty field has meaning, such as an omitted value between two commas.
An empty-string separator has a special, commonly useful behavior: 'cat'.split('') returns ['c', 'a', 't']. The empty string itself split on an empty-string separator produces an empty array, whereas ''.split(',') produces an array containing one empty string. These distinctions matter when writing generic code that may receive empty input.
Splitting a string with '' works in UTF-16 code units, not necessarily user-perceived characters. Some Unicode symbols, including many emoji, are represented by a pair of code units and can be separated into pieces that do not display correctly. If the goal is to process Unicode code points, spreading a string or using Array.from() is often more suitable; grapheme clusters, such as a base character combined with an accent, may require a more specialized approach.
Capturing delimiters and regular-expression details
Normally, separators disappear from the output. If you need to retain a delimiter, put the part of the regular expression to capture in parentheses. For example, 'a=b+c'.split(/([=+]) /) would not match this input because the expression includes a space; the correct pattern is /([=+])/:
const pieces = 'a=b+c'.split(/([=+])/);
// ['a', '=', 'b', '+', 'c']
This can help when tokenizing a small expression or preserving punctuation during a simple transformation. Capturing groups add entries to the array, and unmatched optional captures may appear as undefined, so check the result shape when a pattern has optional groups.
Regular-expression splitting also has edge cases around matches of zero length and matches at string boundaries. JavaScript handles these according to the regular-expression and split rules, but patterns that can match an empty string are often harder to reason about than necessary. Prefer a pattern that consumes at least one character when identifying a separator, and test it with empty input, one-character input, and separators at both ends.
Common mistakes and practical troubleshooting
- Expecting automatic whitespace cleanup:
split(' ')splits on each ordinary space and may preserve empty entries. Usetrim().split(/\s+/)when runs of surrounding whitespace should be treated as one separator. - Using the wrong separator: A dot in
split('.')is a literal dot because the separator is a string. In a regular expression,/./means any character, so a literal period must be escaped as/\./. - Assuming the method edits the string:
split()returns a new array. Keep that return value; calling the method without assigning or using its result does not alter the original string. - Using split for quoted data: Separating CSV text on commas fails when a field can contain a quoted comma, such as
"New York, NY". Use a CSV parser for CSV, and use a parser designed for the relevant format when quoting, escaping, nesting, or other rules are involved. - Forgetting type conversion:
split()is a string method. If a value may benull,undefined, or another type, validate or convert it intentionally before calling the method rather than assuming every value hassplit().
When to use split() and what to use instead
Use split() for straightforward boundaries in a string: words separated by whitespace, path components separated by slashes, or simple fields separated by a known character. It is also useful for turning a short list into an array before applying array operations. For example, 'small|medium|large'.split('|').map(value => value.toUpperCase()) produces an array of uppercase labels.
Choose another approach when the input format has rules beyond simple separators. match() or matchAll() can be more appropriate when you want to find tokens that match a pattern rather than divide around boundaries. A dedicated parser is safer for CSV, JSON, programming languages, or formats with escaping and nested structures. For a basic delimited string that must be reassembled, join() is the common array counterpart: text.split(',').join(';') replaces comma boundaries in uncomplicated input, though it is not a general-purpose replacement tool for structured data.
In short, consider three questions before choosing the method: Is the separator literal or variable? Should empty fields be kept? Does the data have quoting or escaping rules? The answers determine whether a direct string separator, a regular expression, filtering, or a real parser is the most dependable choice.
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.
How do I split a string by spaces in JavaScript?
For one ordinary space, use text.split(' '). To handle multiple spaces, tabs, or line breaks as one boundary, use text.trim().split(/\s+/), if trimming the ends is appropriate.
How do I split a string into characters?text.split('') divides into UTF-16 code units, which can break some emoji or other Unicode characters. For code points, use [...text] or Array.from(text); grapheme clusters may need additional Unicode-aware handling.
How can I keep the separator in the result?
Use a capturing group in a regular-expression separator, such as text.split(/([,;])\s*/). The captured punctuation is inserted into the result array along with the text sections.
Why does split() return empty strings?
Empty strings occur when separators are adjacent or at the beginning or end of the input. They represent sections with no characters. Keep them if blank fields matter, or remove them explicitly when they do not.
Related
- Snowflake SPLIT_PART: Syntax, Examples, and Common Issues
- JavaScript split() Explained: Strings, Limits, and Examples
- Microsoft Access Split Form: How It Works and When to Use It
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Add a Drop-Down List in Excel on SharePointTo add a drop-down list to an Excel workbook stored on SharePoint, open the workbook in Excel, select…
- How to Create a Moving Signature in OutlookTo create a moving signature in Outlook, make or obtain a short animated GIF, then insert it as…
- Customizable Invoice Template in Excel: How to Make OneYes. You can make a customizable invoice template in Microsoft Excel by laying out your business and customer…
- How to Build a Project Schedule in Excel That WorksTo build a project schedule in Excel, list each task with an owner, start date, working-day duration, and…
- Excel Solver: What It Does and How to Use It EffectivelyIn Excel, Solver is an add-in that finds values for selected cells to maximize, minimize, or reach a…
- Delete a Scheduled Email in OutlookYes. In new Outlook or Outlook on the web, open the scheduled message in Drafts, choose Cancel send,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.