Title Case a Sentence better solution

Tell us what’s happening:

I have solved the problem like this is there better way to solve this problem ?

Your code so far


function titleCase(str) {
  str=str.toLowerCase();
  let arr=str.split(" ");
  
  for(let i=0;i<arr.length;i++)
  {
    arr[i]=arr[i].charAt(0).toUpperCase()+arr[i].slice(1);
    // console.log(arr[i]);
  }
  str=arr.join(" ");
  return str;
}
console.clear();
console.log(titleCase("sHoRt AnD sToUt"));

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence

2 Likes

I think the way you have solved it is just fine and I think it is probably already a very good way to solve the problem.

You could use methods like map() and such to make it look more sophisticated and what not, but you will still end up using logic that is very similar to what you have inside the for loop, and you will also likely introduce additional overheads by using and creating additional functions—I’m not suggesting that those methods are necessarily worse (and your choice of method isn’t always just about performance), but my guess is that those methods probably won’t be better than your for loop in this particular case.

That’s just my guess though—and assuming that those other methods involve iteration through an array of substrings of the original string. You can write a few versions and benchmark them if you are really curious. :smile:

I hope that helps!

EDIT: Oh, the only suggestion I forgot to mention is that you can also access the characters in a string like this: "string"[0]; // "s"; I think it’s cleaner, I don’t know what different JavaScript engines do to optimise this vs. charAt(), so… it’s really just a stylistic thing. In addition, I think it’s a good idea to add space between operators, it’s difficult to read at the moment.

2 Likes

thanks man :wink: got some confidence with your comment

I agree with @honmanyau. I came up with a similar solution to yours, @coderharshit, but I used map() instead of the for loop.

Here’s another way to do it that I found either in the fCC guide or on the forum, I can’t remember:

function titleCase(str) {
  return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());
}

This is a nice use of regular expressions and arrow functions.

2 Likes

cool thank you @camper :wink: learned something new.

1 Like