Title Case a Sentence -Improvement

Title Case a Sentence -Improvement
0

#1

Tell us what’s happening:
Hello,

I am supper happy that i could write this code alone without the asking help,
All works fine , now my question is can someone look at it with better experience and give me a similar code witht shorter method of executions

still even though i like mine I want to get other people method to take down what i did in a better format

Your code so far

function titleCase(str) {
  var lowerCase_str = str.toLowerCase();
  var split_str = lowerCase_str.split(" ");
  var correctPhrase = [];
  for (w = 0; w < split_str.length; w++){
    correctPhrase.push(split_str[w].replace(split_str[w][0], split_str[w][0].toUpperCase()));
  }
  var finalPhrase = correctPhrase.join(" ");
  return finalPhrase ;
}

titleCase("MohamED sAid ThaT SHe's noT hIS BesT FrIEND");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36.

Link to the challenge:


#2

This is what i came up with.

function titleCase(str) {
  
  var arr = str.split(" ");
  
  for (var i = 0; i < arr.length; i++) {
    arr[i] = arr[i].substring(0, 1).toUpperCase() + arr[i].substring(1, arr[i].length).toLowerCase();
  }
  
  return arr.join(" ");
}

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

#3

very interesting to read your solutons, which i found very complicated to my level as i don’t know what certain functions do…can you try to play with what i came up with to see what would be the v2.0
thank you


#4

Don’t compare yourself to how others solved it. It’s good to see how others think, but don’t let it get you down if they seem to have a “sexier” solution. You have a good solid solution that works well. Be proud of that.

I might suggest a few minor things to think about. Not that there’s anything wrong with your solution, but a few things might be helpful:

  var lowerCase_str = str.toLowerCase();
  var split_str = lowerCase_str.split(" ");

It’s very common to chain functions. This could be one line:

  var split_str = str.toLowerCase().split(" ");

Of course someone could get carried away with this, but it is clear what is happening here so we can combine the steps and eliminate one variable without making things too confusing.

And a word on naming variables. I don’t like the name split_str because it isn’t a string. I would have called it splitArr.

correctPhrase.push(split_str[w].replace(split_str[w][0], split_str[w][0].toUpperCase()));

I’m not a fan of this logic. In order to understand what is being pushed here, I have to remember that replace by default only replaces the first instance. And at first glance, it is odd to my eye because the reference to “uppercase” is at the end. Again, if I think about it for a second, it makes sense, but I prefer things that are instantly understandable. I would have done:

correctPhrase.push(split_str[w][0].toUpperCase() + split_str[w].slice(1));

To me, this is much more clear. I am combining an uppercase first character with the rest of the the string. Is it “better”? Maybe not, except in the sense that it is a little more intuitive.

And similar to what we did at the beginning, instead of:

  var finalPhrase = correctPhrase.join(" ");
  return finalPhrase ;

I think most people would prefer:

  return correctPhrase.join(" ");

I think with those changes it is a little easier to read. It’s not really “better”, except a little in that sense. There are few variables and some of the similar actions are combined. Of course, you can go overboard with this and create dense, inscrutable code. Sometimes you do want to add “unnecessary” variables and steps to make things more clear. I always say - assume a stranger is reading your code. And if you have to come back to code you wrote six months ago, you will essentially be reading it as a stranger, for the first time. But I think these cuts are beneficial. There certainly are more compact solutions to this challenge, but at some point they get difficult to read. It’s all about balance.

So, this is what I came up with:

function titleCase(str) {
  var splitArr = str.toLowerCase().split(" ");
  var correctPhrase = [];
  for (w = 0; w < splitArr.length; w++){
    correctPhrase.push(splitArr[w][0].toUpperCase() + splitArr[w].slice(1));
  }
  return correctPhrase.join(" ");
}

Again, not better, just a little easier to read, imho. Some things to think about.

vikrant17’s solution is similar to yours, just that instead of creating a new array to push the solution onto, he writes it back into the original array, necessitating one less variable. That’s perhaps a little better. Maybe a little less clear? But in the real world, most coders would understand that, and a comment would clear it up. That solution may also have a tiny advantage that you do the upper and lower casing in situ instead of at the beginning. In you example, you are always converting the first char to lower case and then always converting it to lowercase. Is it a big problem? Not really. But it is ever so slightly less efficient, I would think.

But again, there is nothing objectively wrong with your code. It works well. And my suggestions don’t work any better. Be proud. You are learning how to think algorithmically and learning how to put that into good, solid code. Be proud of that.


#5

Just in case your curious, this is the most compact, “sexiest” solution I could come up with. It uses ES6 and the array method map.

const titleCase = s => s.split(' ').map(w => w[0].toUpperCase() + w.slice(1).toLowerCase()).join(' ')

Is it “better”? Debatable. But you will see stuff like that. If you want to understand it, read up on arrow functions (part of ES6) and the map method. It’s less confusing than you think. You’ll cover these things eventually.


#6

Vikrant explained very well, no need for fancy regexp in this case. Basically the thing is to apply lowercase to string , then break string into array of smaller strings. Then to apply uppercase to every first letter of every string in said array, then join it back together. This is straight forwards as it gets …


#7

I really do appreciation seeing how you made mmy code more sexy.
My whole point was not to put my self in question , or show lack of confidence but as i am learning i want to know how other people would take my method and come up with something else, hence as i understand my base code i will learn from the method and tricks given in the method you did,

I say thank you again

i will keep going and try to solve without checking any solution before hand

I appreciate much your contribution guys


#8

still in the same stile i use, but with different method and thank you for brining me these new methods and solutions


#9

It occurred to me that there is a completely different approach. We index though the string. If the previous char is a space, then the current char should be uppercase, otherwise it should be lowercase:

function titleCase(str) {
  let answer = [str[0].toUpperCase()]
  for (let i=1; i<str.length; i++) {
    answer.push((str[i-1]===' ')?str[i].toUpperCase():str[i].toLowerCase())
  }
  return answer.join('')
}

Is it better? Meh. It’s just a different way to skin a cat.