Title Case a Sentence feedback

Hey guys I just finished “Title Case a Sentence” and I wanted to know some opinions about my code. I feel like I created too many variables but it gets the job done. Is this okay or are there more efficient ways? Did I initialize the variables in the right place?

After finishing I looked at the basic code solution provided by FCC and i don’t get why you would have to rewrite the replace() function…

Also I thought about RegEx, but that would be like shooting ducks with tanks right?

Thanks in advance!

My code


function titleCase(str) {
  let arr = str.toLowerCase().split(' ');
  let firstLetterUppercase = '';
  let wordArray = [];
  let result = [];
  for(let i = 0; i < arr.length; i++){
    // first letter uppercase
    firstLetterUppercase = arr[i].charAt(0).toUpperCase();

    // split word in array
    wordArray = arr[i].split('');

    // replace first letter in wordArray through the big first letter
    wordArray.splice(0,1,firstLetterUppercase);

    // join word array and push to result
    result.push(wordArray.join(''));
  }
  console.log(str + " -> " + result.join(' '));
  return result.join(' ');
}

titleCase("thIS waS HARD Af and I ThinK i crEaTED wAyYY to maNy VaRiAbleS");

Link to the challenge:
Can’t provide a link since I’m knew to the forum.
Javascript Algorithms And Data Structures Certification -> Basic Algorithm Scripting -> Title Case a Sentence

Hi! it’s been a hot minute since I did this challenge but the intermediate answer seems to be inline with what I would do and understand. NOTE: if you understand something that’s all that matters. To me the basic code solution is way to crazy though. I don’t think anyone on that level would come up with that. Using this and making a function just seems way to crazy to me but hey who knows. I prefer the intermediate way using .map(). You loop through the array of words and look for the first char in each of those arrays and replace it with a caps version without making to many variables. Means you only have to .join() once. As for regexes? regexs? regular expressions, I tend to kinda cheese my way and look up a regex I need, somewhere like stack overflow or something. And to answer your tanks shooting ducks question, means a lot less lines of code but I prob wouldn’t understand what the regex was doing. I would just know it works. Basically you say hey if you find something that matches this regex do this aka uppercase it.

1 Like