Opinions in my Title Case Sentece

Opinions in my Title Case Sentece
0

#1

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");

#2

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.


#3

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(' ')

#4

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(' ')

#5

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


#6

One more version, which does not require a split or join.

function titleCase(str) {
  return str
    .toLowerCase()
    .replace(/^(.)|[^\w-'](\w)/gi, match => match.toUpperCase());
}