Title Case a Sentence Test Failing

Tell us what’s happening:

I wrote function titleCase1 but tests are not passing. I copied titleCase function from HINTS, tests are working. Getting similar results with both functions but test are failing except the first one for function titleCase1.

Your code so far

function titleCase1(str) {
    var strArr = str.split(' ');
    var result = '';
    for( var i = 0; i < strArr.length; i++){
      var slicedStr = strArr[i].slice(1).toLowerCase();
      var strUpperCase = strArr[i].charAt(0).toUpperCase();
      var concatStr =  strUpperCase + slicedStr + ' ';
      result += concatStr;
    return result;
function titleCase(str) {
  return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());

console.log(titleCase("I'm a little tea pot"));
console.log(titleCase1("I'm a little tea pot"));
console.log(titleCase("sHoRt AnD sToUt"));
console.log(titleCase1("sHoRt AnD sToUt"));
console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));
console.log(titleCase1("HERE IS MY HANDLE HERE IS MY SPOUT"));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15.

If you compare the strings returned by the two functions for each test case, you will see they are different by a single character at the end. titleCase1 adds an extra character which titleCase does not.

Yes, I just checked with the length property. Thank you so much.

return result.trim();

FYI - The above could be written as both of the following:

var strUpperCase = strArr[i].charAt().toUpperCase(); // defaults to 0 index
var strUpperCase = strArr[i][0].toUpperCase(); // avoids unnecessary call to another function.
1 Like