JavaScript: String.prototype.split
str.split(string_separator)
-
Split the string by separator (a string). e.g.
str.split(",")
Result is array. The separator is not included in result unless using regex arg with capture.
str.split(regex)
-
Split the string by regex. e.g.
str.split(/ +/)
. [see JavaScript: RegExp Syntax]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 of 1 element, the element is the whole string.
str.split("")
- Each char is array element. (Note: if the string contain character whose codepoint ≥ 2^16, such as emoji 😂, the result may be “wrong”.) [see JavaScript: String Code Unit]
String Separator Example
The separator eats the string.
const xx = "abcde".split("c"); console.log(JSON.stringify(xx) === `["ab","de"]`);
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]
Regex Separator Example
Using regex as separator.
const xx = "a b c"; console.log(JSON.stringify(xx.split(/ +/)) === `["a","b","c"]`);
Using regex with capture.
const xx = "a b c"; console.log(JSON.stringify(xx.split(/( +)/)) === `["a"," ","b"," ","c"]`);
[see RegExp Syntax]
Max Length Example
Limit max length.
const xx = `a b c`; console.log(JSON.stringify(xx.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(JSON.stringify("abc".split("-")) === `["abc"]`);