Code Lab

Print every word on its own line

EasyStrings5 min

Write a function printWords(sentence) that prints every word of a string on its own line with console.log.

  • Words are separated by one or more spaces. sentence can also start and end with spaces.
  • Print the words in their order, one word per line, with no spaces around the word.
  • A word is any group of characters between spaces, so punctuation stays with the word: 'Hi, Ann!' has the words Hi, and Ann!.
  • Do not print empty lines. If there are no words (an empty string or only spaces), print nothing.
  • The function does not need to return a value.

Examples

printWords('My Name is Nikhil')

Prints My | Name | is | Nikhil

printWords('  Hi,   Ann! ')

Prints Hi, | Ann!

Extra spaces are skipped, punctuation stays with the word.

Asked at Ness Digital · Source

Loading the editor...
  1. InputprintWords('My Name is Nikhil')
    OutputMy Name is Nikhil
  2. InputprintWords('Hello')
    OutputHello
  3. InputprintWords('I love JavaScript')
    OutputI love JavaScript
  4. Empty string: nothing is printed, not even an empty line

Hidden tests run on Submit.