JS: String.prototype.split

By Xah Lee. Date: . Last updated: .

str.split(string_separator)

Split the string by separator string_separator.

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

str.split(regex)

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.

str.split()

Return array [str].

str.split("")

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

[see JS: Character, Code Unit, 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
b
c`;

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".split("-")
);
// [ 'abc' ]

Reference

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

JS String

  1. String Overview
  2. Template String
  3. Char, Code Unit, Code Point
  4. String Escape Sequence
  5. Unicode Escape Sequence
  6. String to Number
  7. Encode URL, Escape String
  8. Format Number
  9. Source Code Encoding
  10. Allowed Characters in Identifier
  11. String Object
  12. String.prototype

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

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To
  6. Array Object
  7. Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog