Code Lab

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'

Only the first character of a word changes.
capitalizeWords(' two  spaces ')

Returns ' Two Spaces '

Asked at T-Bank · Source

Loading the editor...
  1. InputcapitalizeWords('hello world')
    Expected'Hello World'
  2. InputcapitalizeWords('hello wORLD')
    Expected'Hello WORLD'
  3. InputcapitalizeWords('')
    Expected''

Hidden tests run on Submit.