JS: String.prototype.split

By Xah Lee. Date: . Last updated: .


Split the string by separator string_separator.

Return a array. The separator is not included in result.


Split the string by separator regex.

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

str.split(sep, n)

Return a array of n items at most.


Return array [str].


Return a array, each element is a character. (Note: technically, each element is a code unit.)

[see JS: String Code Unit vs Code Point]

String Separator Example

The separator eats the string.

"abcde".split("c") // [ 'ab', 'de' ]

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

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

Use filter to remove empty string in array.

[see JS: Array.prototype.filter]

Regex Separator Example

Using regex as separator.

const t3 = 'a  b c';
console.log ( t3.split (/ +/) ); // [ 'a', 'b', 'c' ]

Using regex with capture.

const t4 = 'a  b c';
console.log ( t4.split (/( +)/) ); // [ 'a', '  ', 'b', ' ', 'c' ]

[see JS: RegExp Syntax]

Max Length Example

Limit max length.

const tt = `a

console.log (
    tt.split ('\n',2)
); // [ 'a', 'b' ]

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 (
// [ 'abc' ]


ECMAScript 2015 §Text Processing#sec-string.prototype.split

String Topic

  1. JS: Source Code Encoding
  2. JS: String Code Unit vs Code Point
  3. JS: Unicode Character Escape Sequence
  4. JS: Allowed Characters in Identifier
  5. HTML: Allowed Characters in id Attribute
  6. HTML: Character Sets and Encoding
  7. HTML/XML Entity List

  1. JS: Template String
  2. JS: Convert String to Number
  3. JS: Encode URL, Escape String
  4. JS: Format Number
  5. JS: JSON

  1. JS: String Object
  2. JS: String.prototype
  3. JS: String Constructor

RegExp Topic

  1. JS: RegExp Tutorial
  2. JS: RegExp Syntax
  3. JS: Regex Find/Replace
  4. JS: RegExp Object
  5. JS: RegExp Constructor
  6. JS: RegExp.prototype

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon