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)
})
}
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With