Capitalize every word
MediumStrings10 min
Write a function capitalizeWords(text) that returns a copy of the string text in which every word starts with a capital letter: 'hello world' becomes 'Hello World'.
- A word is a run of characters without spaces. Words are separated by the space character
' 'only: a tab or a line break is part of a word, not a separator. - Make the first character of every word upper case with
toUpperCase(). If it is a digit or a sign, it stays the same:'3d model'becomes'3d Model'. - All other characters keep their letter case:
'hello wORLD'becomes'Hello WORLD'. An apostrophe does not start a new word:"don't"becomes"Don't". - Letters with accents count as letters:
'élan'becomes'Élan'. - Keep every space: several spaces in a row and spaces at the start or the end stay where they are. For an empty string return
''.
You can walk over the characters, or split the string on spaces and join the words back. Either way, two spaces in a row are still two spaces in the result (whitespace is not removed).
Examples
capitalizeWords('hello world')Returns 'Hello World'
capitalizeWords('hello wORLD')Returns 'Hello WORLD'
capitalizeWords(' two spaces ')Returns ' Two Spaces '
Asked at T-Bank · Source
Loading the editor...
- Input
capitalizeWords('hello world')Expected'Hello World' - Input
capitalizeWords('hello wORLD')Expected'Hello WORLD' - Input
capitalizeWords('')Expected''
Hidden tests run on Submit