How to print each word in a separate line. Each word is capitalized except the first

Viewed 397

I am trying to create a function that prints each word on a new line. The argument given is a string with words that aren't separated by a space but capitalized except the first word i.e. "helloMyNameIsMark". I have something that works but wondering if there's a better way of doing this in javaScript.

separateWords = (string) => {

  const letters = string.split('');
  let word = "";
  const words = letters.reduce((acc, letter, idx) => {
    if (letter === letter.toUpperCase()) {
      acc.push(word);
      word = "";
      word = word.concat(letter);
    } else if (idx === letters.length - 1) {
      word = word.concat(letter);
      acc.push(word);
    } else {
      word = word.concat(letter)
    }
    return acc
  }, []);
  words.forEach(word => {
    console.log(word)
  })
}
4 Answers

You could use the regex [A-Z] and replace each upper case letter with \n prefix

const separateWords = str => str.replace(/[A-Z]/g, m => '\n' + m)

console.log(separateWords('helloMyNameIsMark'))

Or you could use a lookahead (?=[A-Z]) to split at each upper case letter to get an array of words. Then loop through the array to log each word:

const separateWords = str => str.split(/(?=[A-Z])/g)
separateWords('helloMyNameIsMark').forEach(w => console.log(w))

I would separate the breaking of words into an array and the printing of that array into two distinct functions. Regular expressions make that first part much easier than your reduce call. (But that reduce is a good thought if you don't see a regex solution.)

My version might look like this:

const separateWords = (str) => str .replace (/([A-Z])/g, " $1") .split (' ')

const printSeparateWords = (str) => separateWords (str) .forEach (word => console.log (word) )

printSeparateWords ("helloMyNameIsMark")

Very similar to adiga's answer, but it can actually be simpler:

const separateWords = str => str.replace(/[A-Z]/g, '\n$&');

This will also benefit from improved performance (might matter if used at scale).

Here's a more literal interpretation of your stated requirement: prints each word on a new line.

function separateWords(str){
  let currentWord = '';

  for (let chr of str){
    if (chr == chr.toUpperCase()){
      console.log(currentWord);
      currentWord = chr;
    
    } else {
      currentWord += chr;
    }
  }

  if (currentWord)
    console.log(currentWord);
}

separateWords('helloMyNameIsMark');

Related