Help with Title Case A sentence

Help with Title Case A sentence
0

#1

function titleCase(str) {
var newStr = “”;
var strToArray = str.split(" ");

for(var i = 0; i < strToArray.length; i++){
newStr += strToArray[i].charAt(0).toUpperCase() + strToArray[i].substr(1).toLowerCase() + " ";
}

return newStr;
}

titleCase(“I’m a little tea pot”);
titleCase(“I’m a little tea pot”);
titleCase(“sHoRt AnD sToUt”);
titleCase(“HERE IS MY HANDLE HERE IS MY SPOUT”);

This is my code^. i called the function and it returned what it was supposed to. however, only one function call seems to be working.


#2

Hi,

It is working, but you should only call the function once at a time or you will get the result from the last call only. This is because each call overwrites newSTR.

I added a console log and they all appear in the console, this works because i’m logging inside the function, so each call generates a log.

the double at the end in " " is the return newSTR output.

function titleCase(str) {
var newStr = "";
var strToArray = str.split(" ");

for(var i = 0; i < strToArray.length; i++){
newStr += strToArray[i].charAt(0).toUpperCase() + strToArray[i].substr(1).toLowerCase() + " ";
}
console.log(newStr);
return newStr;
}

titleCase("I'm a little tea pot");
titleCase("I'm a little tea pot");
titleCase("sHoRt AnD sToUt");
titleCase("HERE IS MY HANDLE HERE IS MY SPOUT");
   I'm A Little Tea Pot 
   I'm A Little Tea Pot 
   Short And Stout 
   Here Is My Handle Here Is My Spout 
   "Here Is My Handle Here Is My Spout "

#3

Maybe this could help:

function titleCase(str) {
var newStr = "";
var strToArray = str.split(" ");

for(var i = 0; i < strToArray.length; i++){
newStr += strToArray[i].charAt(0).toUpperCase() + strToArray[i].substr(1).toLowerCase() + " ";
}

console.log(newStr);
}
var calls = [
("I'm a little tea pot"),
("I'm a little tea pot"),
("sHoRt AnD sToUt"),
("HERE IS MY HANDLE HERE IS MY SPOUT")]

for (i = 0; i < calls.length; i++) {
    titleCase(calls[i]);
}`

#4

i tried both of your guys’ codes and they still didn’t work. maybe theres some bug or something


#5

Maybe it doesn’t like extra space at the end of the string? (" " - this)


#6

oh yeh, theres a trailing space

this sorts it

return newStr.slice(0, -1);


#7

Also good thing for removing unneeded spaces at the beginning and end of the string is trim function