JavaScript: String.prototype.split

By Xah Lee. Date: . Last updated: .

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"]`);

Split the string by regex. [see JavaScript: 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";
// [ "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" ]

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

const xx = "a,b,c";
// [ "a,b,c" ]

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 JavaScript: 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. */

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

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

/* solution is use trim first, then regex */
  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