Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
  })
}
like image 525
davyoon Avatar asked Jan 26 '23 03:01

davyoon


1 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))
like image 200
adiga Avatar answered Jan 31 '23 08:01

adiga