For "Title Case Sentence" is this super sloppy?

So I just worked through this and it required a bit of brain power for me. Along the way, I skimmed Sonya Moisset’s article on the three ways of doing this example.

I realize there are a lot of ways to do something with JavaScript which I like but since I’m new to developing with JS I don’t want to learn bad habits. So I’m just looking for code review and feedback, is there any reason why this is “wrong”:

function titleCase(str) {
  var lower = str.toLowerCase().split("");

  for(l=0; l < lower.length; l++) {
    var i = l-1;
   if(lower[i] == " " || lower[i] == null) {
     lower[l] = lower[l].toUpperCase();
   } 
  }
  var final = lower.join("");

  return final;
}

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

Your code is cleaner than mine was when I completed it ~2 months back:

function titleCase(str) {
  var array = str.split(" ");
  var newWord = "";
  for (var i = 0; i < array.length; i++) {
    for (var x = 0; x < array[i].length; x++) {
      if (x === 0) {
      newWord += array[i][x].toUpperCase();
      } else {
        newWord += array[i][x].toLowerCase();
      }
    }
  }
  var sentence = newWord.replace(/([a-z])([A-Z])/g, "$1 $2");
  sentence = sentence.replace(/([A-Z])([A-Z])/g, "$1 $2");
  return sentence;
}

condense

  var final = lower.join("");

  return final;

into

return lower.join("");

also, you shouldn’t leave l as a global variable. Add a var in front of it in your for loop to limit its scope. Plus, you may want to use i in place of l and rename you existing i into something more descriptive.

Thanks for the suggestions, I made those changes.

I see you used a regex, those intimidate me like crazy mostly because I haven’t had much cause to work with them yet.

Well, apparently regex can cause major slowdowns if you don’t know what you’re doing so probably best for us newbs to stay away until the advanced algorithms problems.

Yes, there’s a much simpler way to do it involving .map(). Here’s the code I used:

function titleCase(str) {
  var lowerCase = str.toLowerCase();
  var array = lowerCase.split(" ");
  var upperCase = array.map(function(val) {
    return val[0].toUpperCase() + val.slice(1);
    // Help found at http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript
  });
  return upperCase.join(" ");
}
titleCase("I'm A little tea pot");

Just remember that, while the for loop is really helpful, Javascript has some built in shortcuts like this :slight_smile:

I’m a fan of replace for stuff like this

function titleCase(str) {
  return str.toLowerCase().replace(/\S+/g, function (match) {
    return match[0].toUpperCase() + match.slice(1);
  });
}