Opinions in my Title Case Sentece

hey guys, i just finished this algorithm. I would like to have opinions on the, like if my aproach is the best one and if not how to improve it. Thanks!

  function titleCase(str) {
  var arr = [];
  var splited = str.toLowerCase().split(" ");
  console.log(splited);
  for(var i = 0; i < splited.length; i++){
    arr.push(splited[i].replace(/\w/, function(match){
      return match.toUpperCase();
    }));
  }
  return arr.join(" ");
}

titleCase("sHoRt AnD sToUt");

Your code is clear enough (though you could have removed the console.log line in the middle).

You could operate directly on the split string by using .map().

return str
  .toLowerCase()
  .split(' ')
  .map(function(word) {
    return word.replace(/\w/, function(match) {
      return match.toUpperCase();
    });
  })
  .join(' ');

Here, .map() returns a new array of words whose first letters are uppercased versions of the split string.

By using arrow function syntax, this can be made more concise (although having two arrow functions in one line might look confusing if you’re not used to it)

return str
  .toLowerCase()
  .split(' ')
  .map(word => word.replace(/\w/, match => match.toUpperCase()))
  .join(' ');

I’d probably use /^\w/ instead of /\w/ because it makes it clear that I want to deal with the first character, but that’s personal preference.

1 Like

Another option would be to discard the regexp and just use indexes:

return str
  .split(' ')
  .map(word => word[0].toUpperCase() + word.slice(1).toLowerCase())
  .join(' ')
1 Like

It’s always a good practice to avoid repeatedly calling functions that are applicable to all aspects of your program.

return str
  .toLowerCase()
  .split(' ')
  .map(word => word[0].toUpperCase() + word.slice(1))
  .join(' ')
2 Likes

thanks a lot guys! this answers made a few clicks in my head regarding functions!