Skip to content

Array Join and String Split

join() and split() convert in opposite directions. join() is an array method that returns a string made of the elements with a separator between them. split() is a string method that cuts a string at each separator and returns the pieces as an array.

With no argument, join() separates the elements with a comma. Pass a string to use a different separator, or an empty string to use none. null and undefined elements become empty strings, and every other element is converted with its toString() method.

const ingredients = ['flour', 'butter', 'sugar'];
console.log(ingredients.join());
console.log(ingredients.join(', '));
console.log(ingredients.join(''));
console.log(['a', null, 'b', undefined, 'c'].join('-'));

This prints:

flour,butter,sugar
flour, butter, sugar
flourbuttersugar
a--b--c

split() takes a separator, which can be a string or a regular expression, and an optional limit on how many pieces to return. A regular expression is useful when the separator varies, such as a comma with or without spaces around it. An empty string as the separator splits the string into single characters.

const csvLine = 'Asha,34,London';
console.log(csvLine.split(','));
console.log(csvLine.split(',', 2));
console.log('red ,green, blue'.split(/\s*,\s*/));
console.log('London'.split(''));

This prints:

[ 'Asha', '34', 'London' ]
[ 'Asha', '34' ]
[ 'red', 'green', 'blue' ]
[ 'L', 'o', 'n', 'd', 'o', 'n' ]

A real CSV file can have commas inside quoted values, which a plain split(',') gets wrong, so use a CSV parser for anything beyond simple lines.

split('') cuts a string into UTF-16 code units, not characters. Most emoji, and some other characters, take two code units, so split('') breaks them into halves that cannot be displayed. The spread syntax splits by code point, which keeps each of those together. Some characters people see as one are built from several code points, such as an emoji with a skin tone, and only Intl.Segmenter keeps those whole.

const greeting = 'Hi 👋🏽';
console.log(greeting.split(''));
console.log([...greeting]);
console.log([...new Intl.Segmenter().segment(greeting)].map((part) => part.segment));

This prints:

[
'H', 'i',
' ', '\ud83d',
'\udc4b', '\ud83c',
'\udffd'
]
[ 'H', 'i', ' ', '👋', '🏽' ]
[ 'H', 'i', ' ', '👋🏽' ]

Strings as Arrays has more on treating a string as a list of characters.

The two methods are often used together, with array methods in between, to change a string a word at a time. Here a title is split into words, empty words left by the double space are dropped, each word is capitalised and the words are joined again:

const title = 'the wind in the willows';
const capitalised = title
.split(' ')
.filter((word) => word !== '')
.map((word) => word[0].toUpperCase() + word.slice(1))
.join(' ');
console.log(capitalised);

This prints:

The Wind In The Willows

Steve Griffith covers this topic in his video JavaScript String.split and Array.join.