``
function titleCase(str) {
var array=[];
array = str.toLowerCase().split(' '); //array = [ 'here', 'is', 'some', 'string' ]
var newStr="";
for(var i = 0; i<array.length; i++){
//array[i].charAt(0).toUpperCase(): takes the word from "i-th" location and converts its first character to uppercase
//array[i].substring(1): it gives all characters of the word at "i-th location starting from location 1"
//" " : concatenates space after every word
newStr+=array[i].charAt(0).toUpperCase() + array[i].substring(1) + " ";
// for i=0 => newStr = Here
// for i=1 => newStr = Here Is
// for i=2 => newStr = Here Is Some
// for i=3 => newStr = Here Is Some String
}
return newStr;
}
titleCase("here is some string")
``
After you .split a string, you get an array. And as a matter of fact, array manipulation is a lot more easier, clear, concise and intuitive than string manipulation. You can solve this simple problem by changing your newStr from "" to []. Instead of concatenating to the newStr, .push into newStr. And finally return newStr.join(' ')
function titleCase(str) {
var arr=[];
arr=str.toLowerCase().split(' ');
newStr=[];
for(var i=0;i<arr.length;i++){
newStr.push(arr[i].charAt(0).toUpperCase() + arr[i].substring(1));
}
return newStr.join(' ');
}
titleCase("I'm a little tea pot");
Additionally, you can also leverage your Array.prototype methods and make your code more javascripty, like
function titleCase(str) {
return str.toLowerCase()
.split(' ')
.map(w => w[0].toUpperCase() + w.substr(1))
.join(' ');
}
titleCase("I'm a little tea pot");