Codectionary / Developer documentation / JavaScript

split()

split() divides a string into an array of substrings based on a specified separator, which can be a literal string or a regular expression. It is the inverse operation of Array.prototype.join(). An optional second argument limits the number of resulting elements.

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 characters

Splitting 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 elements

Best 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

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation