Use JavaScript’s String.prototype.split() method to turn a string into an array: call it on the string and provide the separator, such as 'red,green,blue'.split(','), which returns ['red', 'green', 'blue']. The separator can be a literal string or a regular expression; the method returns the pieces between matches, not the separators themselves.
The Basic Syntax
The general form is string.split(separator, limit). The separator determines where the string is divided, and the optional limit caps how many array entries are returned. Neither argument changes the original string: strings are immutable in JavaScript, so split() creates and returns a new array.
const message = 'JavaScript makes strings useful';
const words = message.split(' ');
console.log(words);
// ['JavaScript', 'makes', 'strings', 'useful']
You can also save the result directly, pass it to another function, or use it in an expression. For example, const parts = 'width:640'.split(':'); assigns ['width', '640'] to parts. The values in the array are still strings; splitting text that looks like a number does not convert it to a number. Use a conversion such as Number(parts[1]) when a numeric value is needed.
If you omit the separator, or pass undefined, the result is an array containing the entire original string. For instance, 'hello'.split() returns ['hello'], not an array of characters. That distinction is a common source of confusion.
What the Separator Does
A string separator is matched exactly, including spaces and punctuation. With 'one | two | three'.split(' | '), the exact three-character sequence space, vertical bar, space is removed at each match, producing ['one', 'two', 'three']. If you use only '|' as the separator, the spaces remain at the ends of the resulting pieces.
The separator is not included in the array by default. A separator that does not occur in the string leaves the text intact as one array item: 'blue'.split(',') returns ['blue']. An empty string as the separator is a special case that divides a nonempty string into UTF-16 code units; it does not mean “use whitespace.” For ordinary words separated by any amount of whitespace, a regular expression is usually more appropriate.
Empty pieces can be meaningful. Splitting 'a,,b' on a comma returns ['a', '', 'b'], preserving the empty field between the consecutive commas. Similarly, 'a,b,'.split(',') returns ['a', 'b', ''], because the text ends immediately after a separator. Do not remove these entries unless the data format says empty fields should be ignored.
Choosing a String or Regular Expression
Use a string separator when the delimiter is fixed and literal: a comma, colon, slash, or exact phrase. This is often the clearest choice for simple formats. For example, 'name: Ada'.split(': ') returns ['name', 'Ada']. It will not match a colon without a following space, so choose the delimiter based on the variations your input may contain.
Use a regular expression when one match can take several forms or when separators vary. The expression \s+ matches one or more whitespace characters, including spaces and tabs, so ' red\tgreen blue '.trim().split(/\s+/) returns ['red', 'green', 'blue']. Calling trim() first is useful here: without it, leading or trailing whitespace can create empty entries.
For a line of text that might use either Windows-style CRLF endings or LF endings, text.split(/\r?\n/) handles both common forms. If the input may also contain old-style carriage-return-only line endings, use text.split(/\r\n|\r|\n/). Choose the pattern to match the data you actually expect rather than assuming every source uses the same newline convention.
Using Regular Expressions and Capturing Groups
A regular expression lets split() match a pattern instead of one fixed sequence. For example, '2026-11-03'.split(/-/) returns ['2026', '11', '03']. The regular expression does not need the global flag for this operation. Regex flags such as case-insensitive matching can still affect whether a pattern matches.
Capturing groups make one important difference: captured text is inserted into the result array. For example, '2026-11'.split(/(-)/) returns ['2026', '-', '11']. A group can therefore be useful when the delimiter itself must be preserved, but it can also produce unexpected extra entries. Use a noncapturing group, written (?:...), when grouping is needed only to organize a pattern and the matched text should not appear in the output.
Regular-expression separators can also match a position without consuming visible characters, such as a boundary or lookaround. These patterns are more subtle than splitting on a visible delimiter, particularly around empty matches. If a simple string separator expresses the task clearly, prefer it; when using a zero-width pattern, check the behavior with representative inputs, including an empty string and text that begins or ends at a match.
The Limit Argument and Empty Results
The optional second argument limits the number of entries in the returned array; it does not limit how many characters are examined. With 'a,b,c'.split(',', 2), the result is ['a', 'b']. Any later pieces are omitted rather than joined back into the second entry. A limit of 0 returns an empty array, and a negative numeric limit is converted in a way that generally behaves like a very large limit, so it is not a useful way to request “all but the last item.”
The limit can be handy when only an initial portion is needed. For example, 'host:8080:extra'.split(':', 2) gives ['host', '8080']. But it is not a general-purpose parsing shortcut: if the remaining text matters, split first and then process the resulting array, or choose a parser that understands the full format.
Keep in mind that empty input and a separator that does not match are different cases. ''.split(',') produces [''], because there is no comma match and the original empty string remains the sole piece. In contrast, ''.split('') produces []. These results are useful to know when validating data or writing tests that include blank input.
Unicode and Splitting into Characters
Although split('') looks like a way to get characters, JavaScript strings are represented as UTF-16 code units. Some Unicode symbols use a pair of code units, so splitting an emoji this way can produce two array entries that are each only half of the symbol. For example, a smiling-face emoji may be broken into two pieces that do not display correctly on their own.
For iteration by Unicode code point, use the spread operator or Array.from(): Array.from('A😊') returns ['A', '😊']. This handles surrogate pairs, but it does not necessarily produce user-perceived characters. A visible character can consist of multiple code points, such as a letter combined with a diacritic or an emoji joined to another emoji.
When the task requires user-perceived character boundaries, use Intl.Segmenter where supported by the target JavaScript runtime. With a grapheme granularity, it can segment text into grapheme clusters rather than simply splitting code units or code points. This distinction matters for text editing, counting displayed characters, and processing international text; it is usually irrelevant when splitting ordinary comma-separated fields.
Practical Examples and Common Pitfalls
For a simple list separated by commas, const tags = 'news,science,travel'.split(','); gives an array of three strings. If whitespace around each item is allowed, normalize each item after splitting: const tags = 'news, science, travel'.split(',').map(tag => tag.trim());. The result is ['news', 'science', 'travel']. Trimming is a separate operation; split(',') does not remove spaces automatically.
For a key-value pair with a known first delimiter, split can be a concise starting point. But consider the input rules: 'label: a: b'.split(':') produces three entries, not a key and a value containing the remaining colon. If everything after the first colon belongs to the value, find that first delimiter and slice around its position, or use a parser designed for the format.
A comma-separated line is not necessarily valid CSV. Real CSV can include quoted fields containing commas, escaped quotation marks, and line breaks inside a field. Splitting a CSV row on commas will break such fields into incorrect pieces. For structured formats, use a CSV parser or follow a complete format-aware parsing approach instead of treating every comma as a delimiter.
- Use
split(',')for a simple, known comma delimiter, not for arbitrary CSV. - Use
split(/\s+/)when runs of whitespace should count as one delimiter, and trim first if boundary whitespace is possible. - Check whether empty fields and trailing separators should be preserved.
- Remember that the result contains strings, even when an item looks numeric or boolean.
Alternatives to Split
split() is a good fit when the goal is to collect the pieces around separators. If you want the matches themselves, String.prototype.match() may be clearer. For example, 'cat12dog34'.match(/\d+/g) returns the digit runs ['12', '34'], while splitting on the digit runs returns the text between them.
For cases where a string is divided into only two parts, methods such as indexOf() with slice() can make the “first delimiter only” rule explicit. For well-defined data formats such as JSON or CSV, use the corresponding parser rather than relying on a delimiter split. The best choice depends on whether the input is simple text, a pattern of matches, or structured data with its own escaping rules.
Frequently Asked Questions
How do I split a string by spaces in JavaScript?
Use text.split(' ') for one literal space. To split on one or more whitespace characters, including tabs, use text.trim().split(/\s+/); trimming prevents leading or trailing whitespace from creating empty entries.
How do I convert a string into an array of characters?Array.from(text) or [...text] iterates by Unicode code point. Avoid text.split('') for general Unicode text because it divides UTF-16 code units and may break symbols represented by surrogate pairs. Use Intl.Segmenter when grapheme-level boundaries matter.
Why does split return an empty string in my array?
Each empty string usually corresponds to an empty field, often caused by consecutive separators or a separator at the start or end of the input. For example, 'a,,b'.split(',') preserves the blank field between the commas. Filter empty values only if the input rules say they should be discarded.
Does split change the original string?
No. Strings are immutable, and split() returns a new array without changing the string it was called on. Assign that array to a variable if you need to use it later.
How can I split only at the first separator?split(separator, 2) returns at most two entries, but it discards any later pieces instead of combining them with the second entry. To keep the full remainder, locate the first separator with indexOf() and use slice() on either side of it.
Related
- JavaScript split() to Array: How It Works and Examples
- Balance of Payments: Meaning, Accounts, and Examples
- How to Split an Array in Excel
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel MAX Between Dates: Find the Highest Value in a RangeTo find the largest value recorded between two dates in Excel, use MAXIFS with the value range and…
- Badge Inventory Spreadsheet: Setup and TrackingA badge inventory spreadsheet is a workbook for recording the badges your organization owns, where they are, and…
- Switch Excel Data From Horizontal to VerticalTo switch Excel data from horizontal to vertical, copy the cells, select where the vertical version should begin,…
- Serial Numbers in Excel: Automatic and Manual MethodsTo add serial numbers in Excel, enter 1 and 2 in the first two cells of a numbering…
- How to Insert a Checkbox in Word Online for ChecklistsTo add clickable checkboxes in Word Online, open the document, go to Home, and choose Checklist in the…
- Excel Long Number Format: Display More Digits CorrectlyIn Excel, a long number format changes how a value is displayed, not how many digits Excel can…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.