Use JavaScript’s split() method to divide a string into an array: 'red,green,blue'.split(',') returns ['red', 'green', 'blue']. Choose a separator that marks the boundary you want, such as a comma, a space, or a regular expression.
Basic use of split()
split() is a method of strings. It does not change the original string; it returns a new array containing the pieces. The basic form is string.split(separator, limit), where the separator is optional and the limit is optional.
For example, with a comma-separated value, you can write:
const colors = 'red,green,blue'.split(',');
// ['red', 'green', 'blue']
The separator itself is not included in the resulting pieces. A string can be split on any literal text, not just punctuation:
const path = 'home/projects/site'.split('/');
// ['home', 'projects', 'site']
const words = 'one two three'.split(' ');
// ['one', 'two', 'three']
The result is an ordinary JavaScript array, so you can use array operations such as map(), filter(), and join() on it. If you want to turn the pieces back into a string, call join() with the delimiter you want. Joining does not necessarily reconstruct the exact original if you have removed or changed any pieces.
How the separator affects the result
A separator can be a string or a regular expression. A string separator matches that exact sequence of characters. For instance, splitting on a comma does not also split on a semicolon or a space. If the separator does not occur, the result is an array containing the original string as its only element.
'apples; pears'.split(',');
// ['apples; pears']
Consecutive separators create empty strings between them. This is often useful because it preserves the position of empty fields, but it can surprise you when the input contains repeated punctuation:
'a,,b,'.split(',');
// ['a', '', 'b', '']
A separator at the beginning or end can also produce an empty first or last element. For example, ',a,b'.split(',') returns ['', 'a', 'b']. Do not remove empty values automatically unless that matches the data you intend to keep; an empty field might mean something different from a missing field.
If the separator is omitted, or is undefined, the whole string is returned as a one-item array. An empty string separator behaves differently: it divides the string into pieces between its UTF-16 code units. That distinction matters when choosing a separator and is covered in the Unicode section below.
Using the limit argument
The optional second argument sets the maximum number of elements in the returned array. It does not mean “split at the nth separator and keep the rest together”; it means return no more than that many pieces. Any remaining text after the last included piece is left out.
const parts = 'north,south,east,west'.split(',', 2);
// ['north', 'south']
A zero limit produces an empty array, even if the input is not empty. This can be helpful when a limit comes from a variable, but it is worth checking the value before passing it through:
'a,b,c'.split(',', 0);
// []
The limit is converted to an integer according to JavaScript’s rules. In everyday code, it is clearest to pass a non-negative integer explicitly. Remember that splitting with a limit can discard data. If you need the final field to contain all remaining text, split first and then combine the extra pieces, or parse the input with logic designed for its format.
Splitting with a regular expression
Use a regular expression when one exact delimiter is not enough. For example, to split a string on one or more commas or whitespace characters, pass a regular expression literal:
const fields = 'red, green\tblue'.split(/[\s,]+/);
// ['red', 'green', 'blue']
The plus sign in [\s,]+ means one or more matching characters, so a run of spaces, tabs, or commas acts as a single boundary. Without the plus sign, adjacent matches could create empty elements. Regular expressions are useful for line breaks too: text.split(/\r?\n/) handles both LF line endings and the CRLF sequence commonly found in Windows text files.
Capturing groups in a regular expression separator are included in the output. This behavior can be useful when you want to retain separators, but may be unexpected if the parentheses were added only to group alternatives:
'a-b_c'.split(/([-_])/);
// ['a', '-', 'b', '_', 'c']
Use a non-capturing group, written (?:...), when grouping is needed but the matched text should not appear in the result. For example, 'a-b_c'.split(/(?:-|_)/) returns just ['a', 'b', 'c']. Regular expressions can make parsing more flexible, but keep them readable: a complicated pattern is harder to maintain than a small, clear parsing function.
Common edge cases and mistakes
One frequent mistake is expecting split(' ') to treat any amount of whitespace as one delimiter. It matches a single ordinary space, so repeated spaces create empty entries, and tabs or newlines are not matched. For varied whitespace, use split(/\s+/); if leading or trailing whitespace is possible, trim it first or account for the empty boundary fields:
const words = ' one two '.trim().split(/\s+/);
// ['one', 'two']
Another mistake is assuming that splitting validates or fully parses structured data. Splitting a basic comma-separated list is fine, but a comma may also occur inside a quoted CSV field. For example, splitting 'Mira,"New York, NY"' on commas does not respect CSV quoting. Use a CSV parser for CSV files rather than trying to handle every quoting rule with split().
Likewise, splitting a URL on punctuation is not a substitute for URL parsing, and splitting JSON on commas does not parse JSON. For structured formats, use the relevant built-in parser or a purpose-built library. split() only separates text according to a delimiter; it does not understand the meaning or validity of the content.
Finally, keep in mind that the method returns an array even when no match is found. Code that expects a string after calling split() may fail later. Give the result a name that signals its type, such as parts or fields, and inspect the array before using a particular position.
Unicode and splitting into characters
A common question is how to split a string into characters. Calling text.split('') may look like the answer, but JavaScript strings are represented as UTF-16 code units. Some visible symbols, including many emoji, use a pair of code units, so splitting an empty string can break them into separate pieces.
'A😊B'.split('');
// The emoji is split into two code units
For iteration by Unicode code point, use the string’s iterator, commonly through the spread syntax, or use Array.from():
const codePoints = [...'A😊B'];
// ['A', '😊', 'B']
const alsoCodePoints = Array.from('A😊B');
// ['A', '😊', 'B']
Even code points are not always the same as user-perceived characters. A displayed character can be made from multiple code points, such as a base letter followed by a combining accent, or a joined emoji sequence. If an application needs to divide text into grapheme clusters—the units people generally perceive as characters—use Intl.Segmenter where supported, configured with grapheme granularity. This is a different task from splitting words or fields on a delimiter.
Choosing split() or another approach
Use split() when the input is a string and the boundaries are known or can be described with a manageable regular expression. The choice of approach depends on what the data means, not only on which method produces an array:
- Known delimiter: use a string separator, such as
split('|')for simple pipe-delimited values. - Several equivalent delimiters: use a regular expression, such as
split(/[;,]/)for commas or semicolons. - One match or a particular part: consider
match()or regular-expression methods if you do not need a full array of fields. - Structured input: use a dedicated parser for CSV, JSON, URLs, or another defined format.
- Human-visible characters: use a Unicode-aware iteration or segmentation approach instead of assuming an empty separator is character-safe.
For example, if a string contains a simple list separated by commas, split(',') is clear and sufficient. If the same text follows a formal file format with quoting, escapes, or embedded delimiters, splitting alone is not enough. Choosing the right boundary rule early helps prevent subtle bugs when real-world inputs are less tidy than examples.
Practical examples
To get a filename extension from a simple filename, split on the period and inspect the final element. This is appropriate only if the application’s rules are that simple; hidden files and names with multiple periods may need a more explicit policy.
const fileName = 'report.final.pdf';
const pieces = fileName.split('.');
const extension = pieces.at(-1);
// 'pdf'
at() is a modern array method; in environments where it is unavailable, use pieces[pieces.length - 1]. Another straightforward example is turning a line of tags into trimmed values. Trimming each item prevents spaces around the delimiter from becoming part of the tag:
const tags = 'javascript, arrays, strings'
.split(',')
.map(tag => tag.trim());
// ['javascript', 'arrays', 'strings']
If empty tags should be excluded, add filter(Boolean) after trimming. Do that only when an empty field has no meaning in your data. For debugging, inspect the array directly with console.log(); it makes leading, trailing, and repeated-delimiter empty strings visible.
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 not found?
It returns a one-element array containing the entire original string. For example, 'hello'.split(',') returns ['hello'].
How do I split on spaces, tabs, and newlines?
Use split(/\s+/) to split on runs of whitespace. If the text may begin or end with whitespace, trim it first when removing that whitespace is appropriate.
How do I split a string into characters in JavaScript?
For Unicode code points, use [...text] or Array.from(text). For user-perceived grapheme clusters, use Intl.Segmenter with grapheme granularity; split('') can break some symbols.
Can split() parse a CSV line?
Not reliably in the general case. A comma can appear inside a quoted CSV field, and CSV has additional rules. Use a CSV parser when the input is truly CSV rather than a simple unquoted comma-separated list.
Related
- Balance of Payments: Meaning, Accounts, and Examples
- How to Split an Array in Excel
- Basic Accounting Concepts for Reading a Balance Sheet
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Hanging Indent in Word: Shortcuts and Formatting TipsIn Word for Microsoft 365 on Windows, select the paragraph or paragraphs and press Ctrl+T to create a…
- Lock Cells in Excel: Protect and Unlock a WorksheetYes. In Excel for Microsoft 365 on Windows, select the cells people should be able to edit, open…
- How to Delete a Line in Excel: Rows, Cells, and DataTo delete a line in Excel when you mean a whole row, click its numbered row heading, right-click,…
- Text Join Line Break in Google Sheets: Formula GuideTo join text from several Google Sheets cells on separate lines, use =TEXTJOIN(CHAR(10),TRUE,A2:A5), replacing the range with your…
- Google Sheets: How to Combine Data From Two ColumnsYes. In Google Sheets, combine two columns row by row with the ampersand operator: if the values are…
- Does Excel Save Automatically? AutoSave ExplainedYes, Excel can save changes automatically, but whether it does depends mainly on where the workbook is stored.…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.