In JavaScript, split() is a string method that divides a string wherever a specified separator occurs and returns the pieces in a new array. For example, 'red,green,blue'.split(',') returns ['red', 'green', 'blue']; the original string is unchanged.
What split() Does
Strings often contain several values joined by a delimiter: commas in a simple list, spaces between words, or line breaks between records. split() turns that string into an array so you can access, loop over, or transform the individual pieces. The separator marks where to divide; it is not included in the result unless a regular expression capture group causes it to be included.
The method belongs to strings, not arrays. Call it on a string value, such as text.split(','). It does not edit that value in place. JavaScript strings are immutable, and the result is a separate array; if you need a changed string after processing, you must assign or return a new value.
Syntax and Arguments
The general syntax is string.split(separator, limit). Both arguments are optional, but the separator determines how the input is divided, while the limit caps how many array elements are returned.
- separator: A string or regular expression that identifies each division point. If omitted, or passed as
undefined, the result is an array containing the entire string. - limit: An optional nonnegative integer that limits the number of returned pieces. Any later pieces are left out of the result.
For example, with the string 'one,two,three', calling split(',') produces three items. Calling split(',', 2) produces only ['one', 'two']. The limit does not mean “split at most twice”: it is the maximum length of the returned array.
How Separators Work
A string separator is matched literally. With '2026-11-03'.split('-'), the hyphens mark the boundaries, producing ['2026', '11', '03']. The hyphen is removed from the pieces. A separator can be more than one character: 'a::b::c'.split('::') returns ['a', 'b', 'c'].
If the separator does not occur, JavaScript returns an array containing the unchanged input. For instance, 'hello'.split(',') gives ['hello'], not an empty array. Repeated separators can create empty strings between pieces: 'a,,b'.split(',') returns ['a', '', 'b']. A separator at the end can also create a trailing empty string: 'a,b,'.split(',') returns ['a', 'b', '']. Those empty entries represent real boundaries in the input; remove or filter them only if that matches the data you intend to process.
Using an empty-string separator is a special case. 'cat'.split('') returns ['c', 'a', 't'], splitting the string into UTF-16 code units rather than searching for a visible delimiter. This can be useful for basic ASCII text, but it is not always a safe way to split human-readable Unicode characters, as explained below.
Using Regular Expressions
A regular expression separator lets you divide on a pattern rather than one exact string. For example, 'red, green;blue'.split(/[,;]\s*/) splits on either a comma or semicolon, followed by any optional whitespace. It returns ['red', 'green', 'blue']. This is handy when input uses more than one delimiter or has inconsistent spacing.
Be aware that capturing groups in the regular expression are included in the result. For example, 'a-b'.split(/(-)/) returns ['a', '-', 'b']. If you do not want the separator in the output, use a pattern without a capturing group, such as /(?:-)/, or use a plain string separator when possible. Noncapturing groups begin with ?:.
Regular expressions are useful for simple delimiter rules, but they do not automatically make a complicated text format safe to parse. A pattern that handles commas in a basic list is not necessarily a correct parser for quoted CSV fields, where a comma inside quotes is data rather than a delimiter.
Understanding the Limit
The second argument restricts the number of entries returned, starting from the beginning of the split. With 'a,b,c,d'.split(',', 3), the result is ['a', 'b', 'c']; the remaining text is not added as a final combined item. This detail matters if you want to preserve the unsplit remainder: split() does not provide a “split only the first time and keep the rest together” option through its limit argument.
A limit of zero returns an empty array, even when the string has content. Omitting the limit is usually the right choice when you want every piece. Use a limit when you specifically need to cap the result, such as reading only the first few fields from a known input. Do not use it as a substitute for validating the input: extra data can still exist even though it is not present in the returned array.
Practical Examples
One common use is turning a delimited value into an array and then converting values to another type. For example:
const values = '12,7,25'.split(',').map(Number);
console.log(values); // [12, 7, 25]
Here, split(',') first produces strings, and map(Number) converts each piece to a number. Be cautious with loosely formatted input: converting an empty string with Number('') yields zero, which may not be what your application should accept.
You can also split a simple path or list on a known character:
const pathParts = '/docs/reference'.split('/');
console.log(pathParts); // ['', 'docs', 'reference']
The initial empty string is not a mistake. The path begins with the separator, so the text before that first boundary is empty. If your application wants nonempty path components, filter the result deliberately, for example with .filter(Boolean). That expression also removes every other falsy string-like value after conversion, so use a more explicit condition if empty strings are not the only values you want to exclude.
For a small, predictable list of words, splitting on a literal space can work, but it will not treat tabs or line breaks as separators and may produce empty entries when spaces repeat. A regular expression such as /\s+/ can handle runs of whitespace, usually alongside trimming the ends first.
Whitespace and Empty Values
One frequent surprise is that split(' ') divides only at ordinary space characters. It does not mean “split at any whitespace.” Given ' red green ', it produces empty strings at the beginning, between the repeated spaces, and at the end. A practical approach for ordinary whitespace-separated words is text.trim().split(/\s+/).
Trimming first avoids leading and trailing whitespace creating empty edge entries. However, check for an empty or whitespace-only string before splitting if your desired result is an empty array: ' '.trim().split(/\s+/) returns [''], because splitting the resulting empty string on that regular expression produces one empty piece. You might handle that case explicitly:
const words = text.trim() === '' ? [] : text.trim().split(/\s+/);
The right policy depends on what an empty input means in your program. It could represent no values, one empty value, or invalid data. Decide that intentionally rather than assuming split() will discard empty pieces.
Unicode and Human-Readable Characters
JavaScript strings use UTF-16. As a result, splitting with an empty string separates UTF-16 code units, not necessarily complete Unicode code points or user-perceived characters. Many common letters split as expected, but some symbols, including emoji represented by a surrogate pair, can be broken into separate units. A broken piece may not display as the original character.
If you need to iterate over Unicode code points, Array.from(text) is generally a better choice than text.split(''). For complete user-perceived characters, called grapheme clusters, even code-point iteration may not be enough: a visible character can consist of multiple code points, such as a base letter with a combining mark or an emoji sequence. Where supported in the target runtime, Intl.Segmenter can segment text by grapheme. Choose based on whether you are processing machine-readable tokens, code points, or characters as people see them.
Common Mistakes and Data Boundaries
- Expecting the separator to remain: A plain string separator is removed from the pieces. Use a capturing regular-expression group only when you intentionally want separators in the output.
- Forgetting that pieces are strings: Splitting
'1,2,3'returns string values, not numbers. Convert and validate them if numeric values are required. - Assuming empty entries disappear: Consecutive or edge separators can create empty strings. Filter them only when empty fields are not meaningful.
- Treating split as a CSV parser: Quoted fields, escaped quotes, and embedded line breaks require CSV-aware parsing. A simple comma split can misread valid CSV.
- Calling it on an uncertain value:
split()is a string method. If a variable might benullor a number, validate or convert it first; callingsplit()directly onnullthrows aTypeError.
When converting unknown values, avoid silently turning every value into text unless that is the intended behavior. For example, String(value).split(',') prevents a method error for many values, but it can produce results that do not match the meaning of the original data. Validate the input type and format at the boundary where it enters your program.
Alternatives to split()
Use split() when the goal is to divide a string at every occurrence of a delimiter or pattern. If you need to locate just one part, other string methods may express the intention more clearly. slice() extracts a section by index, while indexOf() can find a delimiter position before you extract text around it. match() is useful when you want values matching a regular expression rather than the text between separators.
If the input follows a structured format such as JSON or CSV, use a parser designed for that format rather than composing a fragile split rule. If you want to inspect individual Unicode text elements, consider Intl.Segmenter instead of splitting on an empty string. The best choice depends on whether the data is a simple delimiter-separated string, a structured document, or human language.
Frequently Asked Questions
Does split() change the original string?
No. Strings are immutable, and split() returns a new array. The original string remains available unchanged.
What does split() return if I omit the separator?
It returns an array containing the whole string as one element. For example, 'hello'.split() returns ['hello'].
How do I split a string by spaces in JavaScript?
For ordinary runs of whitespace, use text.trim().split(/\s+/). Handle empty or whitespace-only input separately if you want an empty array rather than an array containing an empty string.
How can I split on more than one delimiter?
Use a regular expression that matches the possible delimiters, such as text.split(/[,;|]/) for commas, semicolons, or vertical bars. Add whitespace to the pattern if it should be consumed too.
Why does split(”) sometimes break emoji?
An empty-string separator splits UTF-16 code units, which can divide a character represented by multiple code units. Use Array.from() for code points or Intl.Segmenter when you need user-perceived character boundaries.
Can split() parse CSV?
Not reliably for general CSV. Quoted fields may contain commas, quotes, or line breaks, so a simple comma separator cannot distinguish delimiters from data. Use a CSV parser for CSV input.
Related
- T Balance in Accounting: Meaning, Examples, and Uses
- Is Split Fiction Cross-Platform? Crossplay Explained
- Grade 9 Balancing Chemical Equations, Step by Step
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Mail Merge Excel to Word: A Practical Step-by-Step GuideTo mail merge Excel data into Word, prepare a workbook with one row per recipient and a header…
- Nested IFs in Google Sheets: Formulas and AlternativesTo create nested IFs in Google Sheets, put another IF inside the first one’s result: for example, with…
- Out of Office in New Outlook: Set It Up and Schedule ItTo set up an out-of-office reply in New Outlook, open Settings, go to Accounts > Automatic replies, choose…
- Excel Group Rows Count: How to Count Rows in GroupsExcel’s Group command does not calculate a row count; it only lets you collapse or expand selected rows.…
- Add a New Page in Word Without a Header: Step-by-StepTo add a page in the middle of a Word document without a header on that page, isolate…
- Bps Number Format in Excel: Display Basis PointsExcel has no built-in “bps” number format. To show values already stored as basis-point numbers, select the cells,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.