conversion
String.prototype.split
Divides the string into an array of substrings using separator (string or RegExp). With no separator the whole string is returned as a one-element array; with '' each UTF-16 code unit becomes an element.
str.split([separator[, limit]]) Parameters
| Parameter | Purpose |
|---|---|
| separator | String or RegExp to split on |
| limit | Maximum number of pieces to return |
Examples
console.log('a,b,c'.split(',')); Prints [ 'a', 'b', 'c' ]
console.log('hello'.split('')); Prints [ 'h', 'e', 'l', 'l', 'o' ]
console.log('a1b2c3'.split(/\d/)); Prints [ 'a', 'b', 'c' ]
console.log('a,b,c,d'.split(',', 2)); Prints [ 'a', 'b' ]
Gotcha
split('') splits by UTF-16 code units and breaks emoji; use [...str] or Array.from(str) for code-point splitting. limit truncates rather than collecting the remainder.
Related methods
String.prototype.replaceAll
Returns a new string with every occurrence of pattern replaced. Added in ES2021; if pattern is a RegExp it must have the g flag or replaceAll throws TypeError.
String.prototype.matchAll
Returns an iterator of all detailed match results, each including capture groups, index, and input. Added in ES2020 and requires a global (g) RegExp — non-global patterns throw TypeError.
String.prototype[Symbol.iterator]
Returns an iterator that yields the string's Unicode code points as single-character strings, correctly handling surrogate pairs. This is what powers for...of loops and spread over strings.