Splitting strings

When we split a string, the element we split at does not appear in the result. If we split at every empty string, we get the individual characters (including spaces).

// If we split at “space”, no spaces appear in the result:
'two words'.split(' ')           // ⇒ ['two', 'words']

// Periods and other characters still remain:
'This is a sentence.'.split(' ') // ⇒ ['This', 'is', 'a', 'sentence.']

// If we split at a letter, that letter is removed. The space remains:
'hello world'.split('r')         // ⇒ ['hello wo', 'ld']

// If we split at “empty space”, the string is split into all of its
// characters. The space is still in there:
'oh yeah'.split('')              // ⇒ ['o', 'h', ' ', 'y', 'e', 'a', 'h']

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.