Syntax
str.split(separator, limit)Examples
Basic Splitting
Splitting a string on a delimiter character.
const csv = "apple,banana,cherry";
console.log(csv.split(",")); // ["apple", "banana", "cherry"]
const sentence = "The quick brown fox";
console.log(sentence.split(" ")); // ["The", "quick", "brown", "fox"]
console.log("hello".split("")); // ["h", "e", "l", "l", "o"] - split into charactersSplitting with a Regex and Limit
Using a pattern to split on multiple possible delimiters, and limiting results.
const messy = "one, two, three,four";
console.log(messy.split(/,\s*/)); // ["one", "two", "three", "four"]
const limited = "a-b-c-d".split("-", 2);
console.log(limited); // ["a", "b"] - stops after 2 elementsBest practices
- Use split("") only for short strings when you specifically need individual characters - it does not correctly handle some Unicode characters
- Use a regex separator when the delimiter pattern is inconsistent, like extra whitespace around commas
- Combine split() and join() for quick string transformations, like reversing word order in a sentence
- Remember the limit argument truncates the result array - it does not stop the splitting logic from continuing internally
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification