In JavaScript, split() is a string method that divides a string at a chosen separator and returns the pieces in a new array; it is not an array method. For example, 'red,green,blue'.split(',') returns ['red', 'green', 'blue']. If you want to divide an existing array into smaller arrays, use a different approach, such as slice() in a loop.
What split() does
The split() method scans a string for a separator, puts the text between matches into an array, and returns that array. The original string is unchanged because JavaScript strings are immutable. The resulting array can be stored, looped over, sorted, or passed to other array methods.
This makes split() useful whenever data arrives as one string but your code needs separate values. Common examples include a comma-separated list, words separated by spaces, a date written with hyphens, or a path separated by forward slashes. The method does not know what those pieces mean; it only follows the separator you provide.
split() is part of the standard JavaScript String API, so it is available in modern browsers and JavaScript runtimes such as Node.js. The returned value is an ordinary array, but the method itself is called on a string: text.split(','), not items.split(',') when items is already an array.
Syntax and basic behavior
The general syntax is string.split(separator, limit). The separator is the value or pattern that marks each division. The optional limit is a nonnegative number that caps how many array entries the method returns. A separator can be a string or a regular expression.
- String separator: A literal sequence, such as a comma, colon, or space, is searched for in the text.
- Regular-expression separator: A pattern can match multiple possible delimiters, such as spaces or punctuation.
- No separator: If the separator is omitted or is
undefined, the result is an array containing the whole string as one element. - Limit: If supplied, it prevents the result from containing more than the requested number of elements.
For example, with const text = 'north|south|east';, text.split('|') returns three entries. With text.split(), the result is instead ['north|south|east'], because no separator was supplied. That distinction is a frequent source of confusion: calling split() without an argument does not split a string into characters.
Examples with common separators
A comma is a straightforward separator when each value is separated by exactly one comma. With const colors = 'red,green,blue';, colors.split(',') produces ['red', 'green', 'blue']. The comma is removed from the returned values; it does not become an array element.
A space can separate words, but repeated spaces produce empty entries when the separator is the single-space string. For instance, 'one two'.split(' ') returns ['one', '', 'two']. To divide on one or more whitespace characters, use a regular expression: 'one two'.split(/\s+/) returns ['one', 'two']. If the input might have whitespace at either end, trimming first avoids a leading or trailing empty result: ' one two '.trim().split(/\s+/).
A hyphen can separate date components or labels. Given const date = '2026-11-03';, date.split('-') returns ['2026', '11', '03']. Those values are strings, not numbers or date objects. Convert them explicitly if later calculations require numbers, and use a date-aware parser when you need calendar validation or time-zone handling.
When more than one delimiter is valid, a regular expression can match them together. For example, 'a,b; c'.split(/[,;]\s*/) returns ['a', 'b', 'c'], splitting on commas or semicolons and any whitespace immediately after them. The pattern should reflect the actual input format; an overly broad pattern can discard meaningful punctuation.
How the separator affects the result
With a string separator, JavaScript searches for that exact sequence. It does not treat a string such as '.' as a wildcard. Thus, 'a.b.c'.split('.') divides at literal periods. Regular expressions work differently: in a regular expression, a period normally matches any character, so use an escaped period, /\./, when the intended delimiter is a literal full stop.
If the separator appears at the beginning or end, an empty string can appear at the corresponding end of the result. For example, '/home/user/'.split('/') returns ['', 'home', 'user', '']. Those empty elements are not automatically removed. They may be meaningful, or you can filter them if the task calls for it: '/home/user/'.split('/').filter(Boolean) produces ['home', 'user'].
When a regular expression contains capturing parentheses, the captured text is included in the resulting array. For example, 'a1b2'.split(/(\d)/) returns ['a', '1', 'b', '2', '']. This behavior can be useful when the delimiter itself is information you need to retain, but it can surprise readers who expected only the text between matches. Use a noncapturing group, written (?:...), if grouping is needed but the matched delimiter should not be returned.
What the limit argument means
The second argument limits the number of entries in the returned array; it does not limit how many separators are examined in a way that preserves the remaining text as one final piece. With 'a,b,c,d'.split(',', 2), the result is ['a', 'b']. The remaining text, 'c,d', is not added as a third entry. A limit of 0 returns an empty array.
The limit is useful when only the first few fields matter, such as taking the first two components of a simple label. Do not use it as a substitute for validating input. If the string contains fewer separators than expected, the result may contain fewer elements, and reading a missing position gives undefined. Check the array length or validate each field before relying on a fixed layout.
Empty strings and character splitting
Passing an empty string as the separator, as in 'cat'.split(''), returns ['c', 'a', 't']. This differs from omitting the separator. It also has an important Unicode caveat: JavaScript string indexing and this form of splitting operate on UTF-16 code units, so some characters represented by a surrogate pair can be separated into two pieces. Many emoji are examples.
If the goal is to iterate over Unicode code points, use the string iterator, for example [...'🐈'], which produces an array with the cat emoji as one element. This still does not necessarily split a visible user-perceived character into grapheme clusters: some displayed symbols combine multiple code points, such as a base letter and a combining accent. For user-facing text segmentation, the appropriate approach depends on whether the application needs code points or grapheme clusters.
Another edge case is the empty input. ''.split('') returns an empty array, while ''.split() returns an array containing one empty string. The difference follows from whether a separator was supplied, so test the exact form you use rather than assuming every empty string produces the same result.
Why arrays do not have split()
JavaScript arrays already contain separate elements, so the String method split() does not apply to them. Calling ['a', 'b'].split(',') results in a TypeError, because an array has no split method. This is not a limitation of arrays; it is a distinction between dividing text and dividing a collection.
For the reverse operation—combining array elements into one string—use join(). For example, ['red', 'green', 'blue'].join(', ') returns 'red, green, blue'. The relationship is often summarized as split() turns a string into an array and join() turns an array into a string. They are not perfect inverses in every case: joining can lose distinctions, and splitting with a particular separator may not reconstruct the original values unless the format is unambiguous.
If you need to split an array into chunks, use array operations such as slice(), which returns a portion without changing the source array. Here is a helper that groups values in chunks of a chosen size:
function chunkArray(items, size) {
if (!Number.isInteger(size) || size <= 0) {
throw new RangeError('size must be a positive integer');
}
const chunks = [];
for (let start = 0; start < items.length; start += size) {
chunks.push(items.slice(start, start + size));
}
return chunks;
}
chunkArray([1, 2, 3, 4, 5], 2);
// [[1, 2], [3, 4], [5]]
The final chunk can contain fewer items than the requested size, as the example shows. If the input array is empty, the helper returns an empty array. This approach is different from split(): it groups existing values rather than locating delimiters in text. Avoid converting an array to a string with join() just to call split() unless that conversion is genuinely part of the data format, because values, types, and boundaries can be lost.
Common mistakes and safer choices
- Using the wrong method: Call
split()on a string. Useslice()or another array strategy to divide an array. - Expecting spaces to disappear: A delimiter is removed, but surrounding spaces that are not part of the delimiter remain. Trim individual fields when appropriate.
- Assuming the result contains numbers: Split fields are strings. Convert and validate numeric values deliberately.
- Forgetting empty entries: Leading, trailing, or repeated delimiters can create empty strings in the output.
- Treating simple comma splitting as CSV parsing: A value such as
'Smith, Jane'contains a comma inside a quoted field. Splitting that row on every comma breaks the field into pieces. Use a CSV parser for real CSV data, which can include quoting, escaped quotes, and newlines.
For a simple, controlled string such as a list of tags separated by commas, split(',') may be entirely adequate. For external data, consider the format’s rules before choosing a delimiter. A delimiter can also appear inside a legitimate value, whitespace may vary, and malformed input may have missing fields. Correct parsing means accounting for those conditions, not merely getting an array back.
Frequently Asked Questions
Is split() an array method in JavaScript?
No. split() is a string method that returns an array. Arrays do not have a built-in split() method; use array methods such as slice() when you need to make smaller arrays.
How do I split a string into words?
For ordinary whitespace-separated text, use text.trim().split(/\s+/). Trimming prevents leading or trailing whitespace from creating empty entries. If punctuation, quoted phrases, or language-specific word boundaries matter, a simple whitespace split may not be sufficient.
How do I split a string into individual characters?text.split('') divides into UTF-16 code units and can break some Unicode characters. The spread form [...text] handles code points, though it does not combine every multi-code-point grapheme into one displayed character.
How can I split an array into smaller arrays?
Loop through the array in increments of the desired chunk size and use slice(start, end) to create each group. Validate that the size is a positive integer, and decide whether a shorter final chunk is acceptable.
Does split() change the original string?
No. JavaScript strings are immutable, and split() returns a new array. The original string remains unchanged; assigning the result to a variable is necessary if you want to use the separated values later.
Related
- Oracle Split String Example: SQL Methods That Work
- Balance of Payments: How It Works
- Split by Position in Power Query: A Practical Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets COUNTIF: Find Cells with Partial TextYes. In Google Sheets, use COUNTIF with asterisks around the text you want to find: =COUNTIF(A2:A8,"*tea*") counts cells…
- Free UK Wedding Budget Spreadsheet: What to IncludeYes. You can make a free UK wedding budget spreadsheet in Excel for the web or Google Sheets,…
- Excel Number Format to Millions: Steps and ExamplesTo show Excel values in millions without changing the stored numbers, select the cells, press Ctrl+1, choose Custom,…
- Excel Shortcut for Inserting Rows Above or BelowIf you mean a worksheet row, select the row where the new one should go and press Ctrl+Shift+Plus…
- How to Make a Number Negative in Excel: Three MethodsTo make a number negative in Excel, type a minus sign before it, or use a formula such…
- Delete Data Validation in Excel: Steps and OptionsTo delete data validation in Excel for Microsoft 365 on Windows, select the cell or range, choose Data…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.