Skip to content

Split and join

Using split

The .split() method breaks a string in parts and puts them into an array. We specify the string we want to split on.

js
let genresString = 'Fantasy,Sci-Fi,Mystery,Romance'
let genresArray = genresString.split(',')
console.log(genresArray)
console
[ 'Fantasy', 'Sci-Fi', 'Mystery', 'Romance' ]

Individual letters

If we pass an empty string as our split argument, we get an array with all the letters of the original string.

js
let bookTitle = 'Persepolis'
let titleLetters = bookTitle.split('')
console.log(titleLetters)
console
[
  'P', 'e', 'r', 's',
  'e', 'p', 'o', 'l',
  'i', 's'
]

Join

The opposite of splitting is joining. We specify a string to sandwich between the items in an array, and the array is joined into a single string.

js
let bookTitles = ['The Great Gatsby', 'To Kill a Mockingbird', '1984']
let titlesString = bookTitles.join('; ')
console.log(titlesString)
console
The Great Gatsby; To Kill a Mockingbird; 1984