2

The following function should uppercase the first letter of every word in a sentence (str)! Unfortunately it doesn't work and I cant find the solution!

function titleCase(str) {
  let arr = str.toLowerCase().split(" ");
  for (let i = 0; i < arr.length; i++) {
    arr[i].charAt(0).toUpperCase();
  }
  return arr.join(" ");
}

console.log(titleCase("I'm a little tea pot"));
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Possible duplicate of [Convert string to title case with JavaScript](https://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript) – Matsemann Apr 14 '19 at 07:14

3 Answers3

3

You need to assign the result of uppercasing the letter, and concatenate it to the rest of the word:

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

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

It's also easier to use map:

function titleCase(str) {
  return str.split(" ").map(s => s.charAt(0).toUpperCase() + s.substring(1)).join(" ");
}

console.log(titleCase("I'm a little tea pot"));
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

arr is an array of strings, but strings are immutable - simply calling toUpperCase() on a character will just give you a reference to a new, uppercase character, without changing the original string. You need to explicitly reassign the array item:

function titleCase(str) {
  let arr = str.toLowerCase().split(" ");
  for (let i = 0; i < arr.length; i++) {
    arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
  }
  return arr.join(" ");
}

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

Or, perhaps more elegantly, you could use a regular expression. The following uses lookbehind, which works in recent versions of Chrome, Opera, and Node; lookbehind makes for cleaner-looking code, but it's not supported everywhere:

const titleCase = str => str.replace(
  /(?<=^|\s)\S/g,
  firstChar => firstChar.toUpperCase()
);

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

Or, without lookbehind:

const titleCase = str => str.replace(
  /(\S)(\S*)/g,
  (_, firstChar, rest) => firstChar.toUpperCase() + rest
);

console.log(titleCase("I'm a little tea pot"));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You can update your code this way

  • First lowercase all the characters
  • Loop through string indexes
  • If index is 0 or index - 1 is a space character make the str[index] to uppercase
  • Keep appending it a string and return at end

function titleCase(str) {
 let LowerCaseStr = str.toLowerCase()
 let final =''
 for (let i = 0; i < LowerCaseStr.length; i++) {
   if(i === 0 || LowerCaseStr[i-1] === ' '){
     final += LowerCaseStr[i].toUpperCase()
   } else{
     final += LowerCaseStr[i]
   }
 }
return final
}

console.log(titleCase("I'm a little tea pot"));
Code Maniac
  • 37,143
  • 5
  • 39
  • 60