Title case a sentence function I am new to programming. I have written a solution in two different ways, but would like to know what is considered a better solution, and why. 

Additionally, in terms of performance, why would one be considered better?

Solution 1:

function titleCase(str) {
  str = str.toLowerCase();
  str = str.split("");
  str[0] = str[0].toUpperCase();
  for(i = 1; i&lt;str.length; i++){
    if(str[i+1] == " "){
      str[i+2] = str[i+2].toUpperCase();
    }
  }
  str = str.join("");
  return str;
}


Solution 2:

function titleCase(str) {
  str = str.toLowerCase();
  str = str.split(" ");
  str = str.map(function(val){
    val = val.charAt(0).toUpperCase() + val.slice(1);
    return val;
  });
  str = str.join(" ");
  return str;
}
A regular expression is really all you need:

/(^| +)([a-zA-Z])/g


Then use the String#replace method and pass in a function:

function toTitleCase(s) {
    return s.toLowerCase().replace(toTitleCase.WORD_PATTERN, function(match, $1, $2) {
        return $1 + $2.toUpperCase();
    });
}

toTitleCase.WORD_PATTERN = /(^| +)([a-zA-Z])/g;


If you really feel like it, jsperf.com can give you a good idea what the performance is.