Title Case a Sentence, I'm stuck here

Title Case a Sentence, I'm stuck here
0

#1

My code so far:

function titleCase(str) {
   let lowerCase = str.toLowerCase()
   const arr = lowerCase.split(' ').map(el => el.split(''))
   const newArr = arr.map(el => el[0].toUpperCase())
   let result;
   
    for (let i = 0; i < arr.length; i++) {
     let regex = arr[i][0]
      result = str.replace(regex, newArr[i])
   }
   
   return result;
}

titleCase("I'm a little tea pot") // output: I'm a little tea Pot

I don’t wish to look at the solution but I don’t know how else I can solve this challenge, maybe there’s a method I don’t know about or maybe there’s something I’m not seeing.

I need some insight here of how to approach this problem, any help is always appreciated.


#2

This line is the source of problems.
First, you are re-replacing variable result everytime with str.replace. Although str.replace does its job at each iteration, result variable is storing only that change temporaily until next loop.

Also, what is there are multiple instance of same letter that replace method is looking for? It won’t replace the first match it sees.


#3

If I do this str.replace(arr[1][0], newArr[1]) this will return “I’m A little tea pot”, so I have to iterate some how, no?


#4

You are already iterating correctly. You are just not updating the variable correctly after replacing it.

If you are still confused, try this.

Summary
   let result = str;
   
    for (let i = 0; i < arr.length; i++) {
     let regex = arr[i][0]
      result = result.replace(regex, newArr[i])
      console.log(result);
   }