I would like to alternate cases along the string for more than one word. Every word should start with capital letter. I’ve got stuck in the process and don’t know how sort it out.
Example: input: "hello world" / output: "HeLlO WoRlD"
function alternateCase(str) {
if (str.length === 0) {
return ""
}
const arrCapitalised = []
const splitStr = str.split("")
const indexSpace = splitStr.indexOf(" ")
const joinStr = str.split(" ").join("")
for (let i = 0; i < joinStr.length; i++) {
if (i % 2 === 0) {
arrCapitalised.push(joinStr[i].toUpperCase())
} else {
arrCapitalised.push(joinStr[i])
}
}
console.log(arrCapitalised, "PREVIOUS ARRAY")
const finalArr = arrCapitalised.splice(indexSpace, 0, " ")
console.log(finalArr, "FINAL ARRAY")
return arrCapitalised.join("").toString()
}
5
Answers
eAsY…
Here is is:
I transformed the word into an array of characters, then looped once through it and used the upper case into the even letters.
Use of a parsing function gives the most stable result imho. The snippet takes words from a string (the start of a word defined as a letter not preceded by any letter) and converts anyting up to the next ‘not letter’. The first letter is converted to uppercase, the rest of the word to letters with alternating case (the current case of a letter doesn’t matter, see second example)
You could toggle the function for changing the charater and reset if a space is found.
You can just use a boolean flag for the current case and reset that when you hit a space. Also note that you probably should call
.toLowerCase
when inserting a lowercase character, to make the function work correctly for non-lowercase inputs.