JavaScript’s .split() method divides a string into an array of smaller strings, using a separator you provide, and returns that array without changing the original string. For example, 'red,green,blue'.split(',') returns ['red', 'green', 'blue']; the separator can be a string or a regular expression.
What .split() does
.split() is a method on JavaScript strings. It looks for occurrences of a separator, cuts the string at those positions, and puts the pieces into an array. The separator itself is not included in the resulting pieces unless a regular expression capture group makes it part of the result.
Because strings are immutable in JavaScript, the method does not remove text from the original string or otherwise modify it. You can save the returned array, inspect its elements, or use array methods on it:
const parts = 'one-two-three'.split('-');produces an array with three items.parts[0]is'one', andparts.lengthis3.- The original value,
'one-two-three', remains unchanged.
This makes .split() useful when a value has a known delimiter, such as a comma-separated list, a path separated by slashes, or text arranged on separate lines. It is a basic string-parsing tool, not a complete parser for every data format.
Syntax and arguments
The general form is string.split(separator, limit). Both arguments are optional, but the separator determines where the method divides the string, and the limit can cap how many array elements it returns.
- separator: A string or regular expression to search for. If omitted or supplied as
undefined, the method returns an array containing the whole string. - limit: An optional maximum number of elements in the result. For example, a limit of
2returns no more than two pieces.
A frequent misunderstanding is that leaving out the separator splits a string into individual characters. It does not: 'cat'.split() returns ['cat']. To split into character-like units, pass an empty string, while keeping in mind the Unicode limitation described below.
Splitting with a string separator
When the separator is a string, JavaScript searches for that exact sequence of characters. Matching is case-sensitive. For instance, 'a|b|c'.split('|') returns ['a', 'b', 'c'], while 'a|b|c'.split(',') returns ['a|b|c'] because there is no comma to match.
Multi-character separators work the same way. Splitting a date-like value at a hyphen, for example, produces its sections:
const fields = '2026-11-03'.split('-');
The result is ['2026', '11', '03']. The method removes each matched separator, but it does not interpret the meaning of the resulting fields; they remain strings unless your code converts them.
Empty pieces are retained when a separator appears at the beginning or end, or when separators occur consecutively. Thus 'a,,b,'.split(',') returns ['a', '', 'b', '']. Those empty strings can matter: they may indicate a missing field, or they may simply be formatting that your application should ignore. Decide based on the data rather than assuming empty elements disappear.
Splitting with a regular expression
A regular expression lets one separator pattern match more than one exact string. This is handy when input may use several delimiters or inconsistent spacing. For example, 'red, green; blue'.split(/[,;]\s*/) returns ['red', 'green', 'blue']. The pattern matches either a comma or semicolon, followed by any whitespace characters.
Regular expressions can also handle repeated whitespace. 'alpha beta\tgamma'.split(/\s+/) returns ['alpha', 'beta', 'gamma'], because \s+ matches one or more whitespace characters, including spaces and tabs. A string separator of one space would not treat a run of several spaces as a single delimiter.
Capturing groups are a notable exception to the rule that separators disappear. If the regular expression contains a capturing group, the matched capture is inserted into the result. For example, 'a=1;b=2'.split(/([=;]) /) would not match as intended because the sample text has no space after each separator. With the matching pattern /([=;]) /, spaces are required; with /([=;])/, the result includes the equals signs and semicolons between the other pieces. Use a non-capturing group, such as /(?:,|;)/, when grouping alternatives but not retaining the delimiter.
What the limit does
The second argument restricts the number of items in the returned array; it does not specify how many separators to remove. With 'a,b,c'.split(',', 2), the result is ['a', 'b']. Once the result reaches the limit, later content is not returned. This is useful when only the first few fields matter, but it also means the remaining text is not automatically joined into a final field.
A limit of zero produces an empty array, as in 'a,b'.split(',', 0). If the limit is omitted, the result can contain all the pieces. In everyday code, use a small positive integer when you specifically want to cap the output, and check that doing so will not discard information your program needs.
Empty strings, characters, and Unicode
The behavior of an empty separator is different from omitting the separator. 'bird'.split('') returns ['b', 'i', 'r', 'd'], dividing the string into UTF-16 code units. For ordinary English letters this looks like a character-by-character split, but it is not a safe way to divide every Unicode character.
Some visible symbols are represented by multiple UTF-16 code units. An emoji such as '💡' may therefore be divided into parts that are not meaningful standalone characters by .split(''). If you need Unicode code points rather than UTF-16 code units, use Array.from(text) or the spread syntax, such as [...text]. Even those do not necessarily group every multi-code-point grapheme, such as a combined emoji sequence, into one user-perceived character; specialized grapheme segmentation may be needed for that.
Empty input has a related distinction: ''.split(',') returns [''], because there is no comma to split at, whereas ''.split('') returns an empty array. Test the exact input and separator combinations relevant to your code if empty values have special meaning.
Practical patterns and common mistakes
For line-oriented text, a regular expression can accommodate both common newline forms: const lines = text.split(/\r?\n/);. Here, \r? allows an optional carriage return before the newline, so the expression handles line feeds and carriage-return-plus-line-feed sequences. If blank lines should be ignored, filter them explicitly rather than expecting .split() to remove them.
For a simple list of tags separated by commas, a small cleanup step may be appropriate:
const tags = input.split(',').map(tag => tag.trim()).filter(Boolean);
This splits on commas, trims spaces around each item, and removes empty strings. It is a practical pattern for uncomplicated input, but it intentionally discards blank fields. If blanks are meaningful, omit the filter or handle those fields separately.
Keep these common issues in mind:
- Splitting is not trimming.
'a, b'.split(',')gives['a', ' b']; the leading space remains until you calltrim(). - A delimiter may be absent. If no match exists, the result is an array containing the original string, not an empty array.
- Trailing empty fields remain. A final delimiter can produce a final empty string, which may affect validation and array lengths.
- Simple splitting is not full CSV parsing. A comma inside a quoted CSV field is not necessarily a field boundary. Real CSV can also involve escaped quotes and newlines, so use a CSV parser for general CSV data.
How .split() compares with alternatives
Use .split() when the goal is to turn one string into an array at predictable separators. If you only need to check whether a string contains a piece of text, includes() is more direct. If you need to find where a match occurs, consider indexOf() or regular-expression matching methods rather than creating an array of all sections.
If you need to change separators while keeping the result as one string, replace() may be a better fit. If the input has nested structure, quoting rules, or a formal grammar, a dedicated parser is more reliable than a chain of splits. For example, splitting a simple URL path on '/' may be adequate for a known, controlled path, but it does not by itself parse every component or account for encoding rules.
Frequently Asked Questions
Does JavaScript .split() change the original string?
No. Strings are immutable, and .split() returns a new array. The original string remains the same.
How do I split a string into an array of characters?
For basic text, text.split('') separates UTF-16 code units. For Unicode code points, use Array.from(text) or [...text]; neither necessarily groups every visual grapheme into one item.
How do I split on spaces, commas, or semicolons?
Use a regular expression such as text.split(/[ ,;]/) for any one of those characters. Use a pattern like /\s+/ when any run of whitespace should count as one separator.
Why does .split() return an empty string?
A separator at the start or end, or two separators next to each other, creates an empty field. For example, 'a,,b'.split(',') includes an empty string between the commas.
What happens when the separator is omitted?
The whole string is returned as the only element of an array. To split at a delimiter, pass that delimiter; to split into UTF-16 code units, pass ''.
Related
- Split a Part in Onshape: Steps, Uses, and Fixes
- Excel Goal Seek on Multiple Cells Explained
- JavaScript split() to Array: How It Works and Examples
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Dependent Dropdown List: Group Choices by CategoryYes. In Excel for Microsoft 365, make a group dropdown and a second dropdown that changes to show…
- Excel Color Codes: How to Apply, Save, and Reuse ThemTo give a cell a specific color code in Excel for Microsoft 365 on Windows, select the cell…
- How to Set Your Out of Office in New Outlook: Step by StepIn New Outlook, open Settings (the gear icon), go to Accounts > Automatic replies, turn on automatic replies,…
- Attendance and Payroll Excel Template: Setup GuideYes. An attendance and payroll Excel template can track employee clock-in and clock-out times, calculate hours, summarize regular…
- Track Changes Options in Microsoft Word: Where to Find ThemTo get to Track Changes options in Microsoft Word for Microsoft 365 on Windows, open the document, select…
- How to Hide Page Numbers in Excel Before PrintingTo hide page numbers that will print from an Excel worksheet, open Page Layout > Page Setup using…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.