JavaScript split(): Tokenize with Explicit Separators
Quick answer
Split produces an array of substrings separated by a literal string or pattern. It is useful for simple delimited data.
How it works
text.split(separator, limit) includes empty fields around adjacent separators and limits the number of output elements, not the number of splits. Omitting the separator returns an array containing the original string, unless the limit is zero. An empty separator splits into UTF-16 units.
console.log(JSON.stringify("a,,b,".split(",")));Expected output in Node.js:
["a","","b",""]Adjacent and trailing delimiters produce empty fields.
console.log(JSON.stringify("red|blue|green".split("|", 2)));Expected output in Node.js:
["red","blue"]Only the first two resulting elements are retained.
Common mistakes
Splitting on commas is not a CSV parser: quoted fields can contain commas. Use a real parser for structured formats.
Practice
Tokenize a simple pipe-delimited record including empty fields.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript split(): Tokenize with Explicit Separators — Knowledge Check
Apply the taught concept and predict the output.
What does split limit restrict?
How are two adjacent literal separators represented in the output?
Why is split("") unsuitable for counting emoji characters?
What is the exact console output in JavaScript split(): Tokenize with Explicit Separators example 1?
console.log(JSON.stringify("a,,b,".split(",")));What is the exact console output in JavaScript split(): Tokenize with Explicit Separators example 2?
console.log(JSON.stringify("red|blue|green".split("|", 2)));