Title Case a Sentence help

After much deliberation and googleing I found a code that works but it doesn’t add a space in between the words. Any advice? Thank you.

function titleCase(str) {
var array=[];
array = str.toLowerCase().split(’ ');
var newStr="";

for(var i = 0; i<array.length; i++){
newStr+=array[i].charAt(0).toUpperCase() + array[i].substring(1);

}

return newStr;
}

``
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")
``

There’s a slight problem with this. It also adds a space at the end of the final string. But it’s not hard to fix :slight_smile:.

Oh yes!Check inside the loop if it is last word then don’t add space.

Or alternatively, let it add the space then use .trim() at the end.

1 Like

Yes…you can do it this way also

1 Like

How do I get rid of the last space?

Found this at last-

function titleCase(str) {
  var arr=[];
  arr=str.toLowerCase().split(' ');
  newStr="";
  
  for(var i=0;i<arr.length;i++){
    newStr+=arr[i].charAt(0).toUpperCase() + arr[i].substring(1) + " ";
  }
  
  return newStr.trim();
}

titleCase("I'm a little tea pot");


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");