JS: String.prototype.split

By Xah Lee. Date: . Last updated: .
str.split(sep_str)

sep_str is a string type. (not regex)

Split the string by separator sep_str.

Result is Array. The separator is not included in result.

console.log("ab cd".split(" "));
// [ "ab", "cd" ]
str.split(regex_obj)

Split the string by regex_obj. [see JS: Regular Expression Syntax]

If regex_obj contains capturing parentheses, the captured parts are included in result.

// split string by regex
const xx = "a     b c";
console.log(xx.split(/ +/));
// [ "a", "b", "c" ]
// split string by regex with capture, to include the separator in result
const xx = "a-b-c";
console.log(xx.split(/(-)/));
// [ "a", "-", "b", "-", "c" ]
str.split(sep, n)

get just the first n items.

const xx = "a,b,c,d";
console.log(xx.split(",", 2));
// [ "a", "b" ]
str.split()

Return array of 1 element, the element is the whole string.

const xx = "a,b,c";
console.log(xx.split());
// [ "a,b,c" ]
str.split("")

Return array, each element is the code unit.

console.log("abc".split(""));
// [ "a", "b", "c" ]

console.log("a🦋c".split(""));
// [ "a", "�", "�", "c" ]

Example. repeated space

Repeated space in string may result empty string element in array.

/* Repeated space in string may result empty string element in array. */

console.log(
 " a  b c ".split(" "),
);
// [ "", "a", "", "b", "c", "" ]

// using regex still have problem at the edges
console.log(
 " a  b c ".split(/ +/),
);
// [ "", "a", "b", "c", "" ]

// solution is use trim first, then regex
console.log(
 " a  b c ".trim().split(/ +/),
);
// [ "a", "b", "c" ]

see also JS: Array.prototype.filter

Example. separator not in string

// split by a char that doesn't exist, returns array of the full string
console.log("abc".split("-"));
// [ "abc" ]