JS: String.prototype.split

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

Split the string by separator (a string).

Result is Array. The separator is not included in result unless using regex arg with capture.

const xx = "ab cd".split(" ");
console.log(JSON.stringify(xx) === `["ab","cd"]`);
str.split(regex)

Split the string by regex. [see JS: RegExp Syntax]

If regex 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("")

Each char is array element.

🛑 WARNING: If the string contain character whose codepoint ≥ 2^16, such as emoji 😂, the result is not what expected. [see JS: String Code Unit]

String Separator Example

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

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

console.log(
  JSON.stringify(" a  b c ".split(" ")) === `["","a","","b","c",""]`,
);

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

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

Use filter to remove empty string in array.

[see Array.prototype.filter]

Other Example

Split by a character that doesn't exist, return full string

// split by a char that doesn't exist, returns full string
console.log(JSON.stringify("abc".split("-")) === `["abc"]`);
BUY ΣJS JavaScript in Depth