I have this two function that make the first letter of every word capitalize while the rest of the word is in lower case.
I compare the return of every function with the final result desire, but my function return false and the function with map return true. Some one know why?
let str1 = "I'm a little tea pot"
let str2 = "sHoRt AnD sToUt"
let str3 = "HERE IS MY HANDLE HERE IS MY SPOUT"
function titleCase(str) {
let toArray = str.split(" ")
let allCapitalize = ""
for (let x of toArray) {
allCapitalize += x.charAt(0).toUpperCase() + x.slice(1).toLowerCase() + " "
}
return allCapitalize
}
function titleCaseMap(str) {
return str.split(" ").map((x) => {
return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
}).join(" ");
}
console.log(titleCase(str1));
console.log(titleCase(str2));
console.log(titleCase(str3));
console.log(titleCase(str1) === "I'm A Little Tea Pot"); //false
console.log(titleCase(str2) === "Short And Stout"); //false
console.log(titleCase(str3) === "Here Is My Handle Here Is My Spout"); //false
console.log(titleCaseMap(str1))
console.log(titleCaseMap(str2))
console.log(titleCaseMap(str3))
console.log(titleCaseMap(str1) === "I'm A Little Tea Pot"); //true
console.log(titleCaseMap(str2) === "Short And Stout"); //true
console.log(titleCaseMap(str3) === "Here Is My Handle Here Is My Spout"); //true
the titleCase
function always add an extra space at the end.
You should update it such that the space is not added at the end.
I updated the function to this:
function titleCase(str) {
let toArray = str.split(" ")
let allCapitalize = ""
for (let i = 0; i < toArray.length; i++) {
let x = toArray[i];
if (i > 0) {
allCapitalize += " ";
}
allCapitalize += x.charAt(0).toUpperCase() + x.slice(1).toLowerCase();
}
return allCapitalize
}