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