Title Case A Sentence - String.prototype.split()?

Title Case A Sentence - String.prototype.split()?


I just finished this exercise and I’m confused as to why String.prototype.split() was mentioned. I completed successful code without it and even though the code works I’m wondering if there is a specific reason to use the .split method. For instance, cross-browser compatibility is one thing that came to mind.

I’d hate to be forming bad habits so early on. If anyone has a moment to look at my code and let me know if it’s OK or if I’ve committed some terrible act of coding I’d really appreciate it. It’s short but it kind of looks like a train wreck. ^_^;

Code below under Summary.

function titleCase(str) {  

  // change string to lowercase and use RegExp to cap the first letter of each word
  str = str.toLowerCase().replace(/(^|\s)[a-z]/g, function(cap) {
    return cap.toUpperCase();

  return str;

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


There’s nothing wrong with your code, though I’m sure that using split() and array access would be a few milliseconds faster for huge strings.


@PortableStick Thanks for your reply! I knew there was probably some reason to consider other methods. Time, even in milliseconds, is a good thing to keep in mind.