JavaScript’s split() method divides a string into an array of smaller strings, using a separator you provide. For example, "red,green,blue".split(",") returns ["red", "green", "blue"]; the original string is not changed.
What split() Does
split() is a method of JavaScript strings. It searches the string for occurrences of a separator and returns the pieces between them as elements in a new array. The separator can be a string, a regular expression, or omitted. This makes the method useful for turning delimited text into a list of values, extracting words, or breaking text at a pattern.
The method does not remove or modify characters in the original string. It returns an array, even when there is only one resulting piece. For instance, splitting "hello" on a comma returns ["hello"], not the string "hello". To use array operations such as map() or join() on the result, remember that it is an array rather than a string.
Syntax and Parameters
The basic syntax is string.split(separator, limit). The first argument controls where the string is divided; the optional second argument limits how many array elements are returned. Both arguments have meaningful edge cases, so choose them based on the input format rather than assuming every string is well-formed.
separator: A string or regular expression that marks each division. The matched separator is normally left out of the resulting pieces. If the argument is omitted or isundefined, the method returns the original string as a single array element.limit: An optional maximum number of elements in the returned array. If the limit is reached, later pieces are not included. A limit of zero returns an empty array.
For example, with the string "one|two|three", calling split("|") gives three elements. Calling split("|", 2) gives ["one", "two"]. The limit does not mean “split at exactly this many separators and then preserve the rest”: it limits the number of output elements, so the remaining text after the second piece is omitted.
Splitting on a String Separator
A string separator is usually the clearest option when the input uses a known delimiter, such as a comma, pipe, or colon. For example, "2026-11-03".split("-") returns ["2026", "11", "03"]. The hyphens themselves do not appear in the result.
Separators can contain more than one character. Splitting "first::second::third" on "::" uses each complete pair of colons as one delimiter. A separator is matched literally in this case; characters such as a period or a plus sign do not become regular-expression operators unless you pass a regular expression.
Whitespace deserves attention. Splitting on a single space only matches a single space character, so multiple spaces can produce empty elements. Tabs and line breaks are different characters and will not match a space. If the goal is to divide text wherever one or more whitespace characters occur, a regular expression such as /\s+/ is often more suitable.
Using Regular Expressions
Passing a regular expression lets you describe a pattern rather than one fixed separator. For example, "apples, pears; plums".split(/[,;]\s*/) returns ["apples", "pears", "plums"]. The pattern matches a comma or semicolon and any whitespace immediately after it, so those delimiters are not retained in the pieces.
Capturing groups are a notable exception to the usual rule that separators disappear. If the regular expression contains capturing parentheses, the text matched by each capture is inserted into the result array. For example, "a-b".split(/(-)/) returns ["a", "-", "b"]. Use a non-capturing group, written (?:...), when grouping is needed but the matched delimiter should not be included.
Regular expressions can be powerful, but they are not automatically the best choice. For one fixed delimiter, a string separator is generally easier to read. Use a regular expression when the boundary can vary—for example, when the text may contain commas or semicolons, or when whitespace of different lengths should count as one boundary.
Empty Separators and Empty Strings
Passing an empty string as the separator asks JavaScript to split the string between its UTF-16 code units. Thus, "cat".split("") returns ["c", "a", "t"]. This can be useful for simple strings, but it is not always a safe way to split text characters: some visible symbols are represented by multiple code units and can be broken apart.
For example, many emoji are represented by a surrogate pair or a longer sequence of Unicode code points. Splitting such text with an empty string can yield pieces that are not the individual visible characters a reader expects. If you need to iterate by Unicode code point, Array.from(text) is generally more suitable. Even code points are not always the same as user-perceived characters: a letter combined with a diacritic, or an emoji joined with another symbol, can form one grapheme cluster from multiple code points.
An empty input string also has results worth knowing. "".split(",") returns [""], since there is no comma and the whole string is the one piece. By contrast, "".split("") returns an empty array. These differences can matter when validating input or counting values, so test empty input explicitly.
Common Uses and Practical Examples
One everyday use is turning a simple delimited value into an array. With a pipe-separated string in a variable, const tags = "news|science|design".split("|"); produces an array that can be searched or looped over. When the input may have spaces around each item, split first and then trim each piece:
const names = "Ada, Grace, Linus"
.split(",")
.map(name => name.trim());
The resulting array is ["Ada", "Grace", "Linus"]. Trimming is a separate step: split(",") does not automatically remove spaces from the beginning or end of each piece.
Another use is extracting parts of a simple path or identifier. For example, "user:42".split(":") returns ["user", "42"]. If the format guarantees exactly two parts, you might assign them with array destructuring: const [type, id] = "user:42".split(":");. If the input is not guaranteed to follow that format, check the array length and contents before relying on those variables.
For text that needs joining again, arrays provide the complementary join() method. For example, splitting "a/b/c" on "/" and joining the result with "-" produces "a-b-c". This is a transformation of the text, not a way to preserve the original separators: if the original delimiter types or spacing matter, splitting alone may discard information you need.
Common Problems and Misconceptions
A frequent surprise is getting empty strings in the result. Consecutive separators, or a separator at the beginning or end, can create empty pieces. For example, "a,,b".split(",") returns ["a", "", "b"], while ",a,".split(",") returns ["", "a", ""]. Those empty values represent the text between adjacent boundaries; they are not automatically removed.
If empty entries should be discarded, filter them explicitly. If whitespace-only pieces should also count as empty, trim before filtering:
const parts = "a, ,b,,c"
.split(",")
.map(part => part.trim())
.filter(Boolean);
This returns ["a", "b", "c"]. Be aware that filter(Boolean) removes every falsy value. For arrays of strings, that means empty strings; if a more specific rule is needed, use a predicate such as part => part !== "".
Another misconception is that split(" ") means “split on any amount of whitespace.” It does not: it matches one ordinary space at a time. A regular expression like /\s+/ handles runs of whitespace, but leading or trailing whitespace can still create an empty first or last element. Trimming the full string before splitting can address that specific case, as in text.trim().split(/\s+/). Decide separately what an all-whitespace input should produce, because trimming it results in an empty string.
Finally, split() is not a parser for every structured format. A comma-separated list that allows quoted fields, such as a CSV file, cannot be handled reliably by splitting on commas alone: commas inside quoted fields are not delimiters. Use a CSV parser for CSV data, and use a URL parser for URLs rather than assuming that splitting on punctuation will account for encoding and syntax rules.
split() Compared with Related Methods
Choose split() when the desired result is the pieces of a string as an array. Choose replace() when the goal is to change or remove matching text while keeping the result as a string. For instance, replacing a comma with a semicolon changes the delimiter without creating an array; splitting on the comma creates separate values.
match() and matchAll() serve different needs when working with regular expressions. They are useful when you want the text that matches a pattern, or match details, rather than the text between separators. The choice depends on whether the pattern describes the items you want to collect or the boundaries between them.
For a fixed delimiter, split() is often simpler than manually searching with indexOf() and slicing. Manual parsing can still be appropriate when you need precise control over malformed input, preserve delimiter positions, or process a large input incrementally. For complex grammars and data formats, a dedicated parser is safer than building a fragile chain of splits.
Frequently Asked Questions
Does JavaScript split() change the original string?
No. Strings are immutable in JavaScript, and split() returns a new array of pieces. The original string remains unchanged.
What happens if I call split() without a separator?
Calling text.split(), or passing undefined as the separator, returns an array containing the entire string as one element. It does not split into characters.
How do I split a string by spaces in JavaScript?
Use text.split(" ") for single ordinary spaces. To split on one or more kinds or runs of whitespace, use text.split(/\s+/), and consider trimming the text first if leading or trailing whitespace should not create empty pieces.
How can I remove empty values after split()?
Chain filter() after splitting, such as text.split(",").filter(value => value !== ""). If spaces should be ignored too, trim each value before filtering.
Can split() divide a string into characters?text.split("") divides between UTF-16 code units, which can break some emoji and other Unicode characters. For code points, use Array.from(text); for visible grapheme clusters, use a grapheme-aware approach such as Intl.Segmenter where supported.
Does split() work with commas in quoted CSV fields?
Not reliably. Splitting on a comma treats every comma as a delimiter, including commas inside quoted fields. Use a CSV parser that understands quoting and escaping rules.
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
- Excel Column Won’t Unhide? Causes, Checks, and FixesIf an Excel column will not unhide, select the columns on both sides of it—or select the whole…
- Remove a Section Break in Word Without Wrecking LayoutTo remove a section break in Microsoft Word for Microsoft 365 on Windows, choose Home > ¶ to…
- Open Excel Files in the Desktop App from the WebTo open a workbook you are viewing in a browser in the Excel desktop app, choose Open in…
- Share an Outlook Calendar So Others Can EditTo let someone edit an Outlook calendar, open Calendar, choose Share Calendar, enter their email address, set the…
- Excel Solver Simplex LP: When to Use It and How It WorksExcel Solver’s Simplex LP method finds the best value for a linear objective while meeting linear constraints. In…
- Open Excel Files Online: Your Options ExplainedYes. To open an Excel file online, sign in to Microsoft 365 or OneDrive with a Microsoft account,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.