The String split() method
By Flavio Copes
Learn how the JavaScript split() method breaks a string into an array of tokens every time it finds a separator pattern, with the case-sensitive match removed.
split() breaks a string into an array of tokens every time it finds the separator you pass to it. The match is case sensitive, and the separator itself is removed from the result:
const phrase = 'I love my dog! Dogs are great'
const tokens = phrase.split('dog')
tokens //["I love my ", "! Dogs are great"]
Notice that Dogs did not match, because the separator was lowercase dog.
You reach for split() any time you have one string that contains several pieces of data. A comma-separated line is the classic case:
const csv = 'Flavio,38,Milan'
csv.split(',') //['Flavio', '38', 'Milan']
Or a sentence you want to break into words:
'the quick brown fox'.split(' ') //['the', 'quick', 'brown', 'fox']
What happens with edge cases?
If the separator is not found, you get an array with the whole string as its only item:
'hello'.split(',') //['hello']
If you call split() with no argument at all, you get the same thing: the entire string wrapped in an array.
An empty string as separator splits the string into individual characters:
'ciao'.split('') //['c', 'i', 'a', 'o']
Limiting the number of results
split() accepts a second argument, the maximum number of tokens to return:
'one,two,three,four'.split(',', 2) //['one', 'two']
Everything after the limit is discarded, not merged into the last token.
Splitting with a regular expression
The separator can also be a regular expression. This is handy when the input is messy, for example when words are separated by a variable number of spaces:
'apples and oranges'.split(/\s+/) //['apples', 'and', 'oranges']
Be careful with emojis
Splitting by the empty string works character by character, but JavaScript strings are sequences of UTF-16 code units. Characters outside the basic range, like most emojis, take two code units, and split('') breaks them apart:
'hi🐶'.split('') //['h', 'i', '\uD83D', '\uDC36']
The fix is to use the spread operator instead, which iterates the string by full characters:
[...'hi🐶'] //['h', 'i', '🐶']
One last tip: split() and join() are natural companions. Split a string into an array, transform the items, then join() them back into a string.
Related posts about js: