dwyl / learn-javascript

A Series of Simple Steps in JavaScript :-)
Other
64 stars 15 forks source link

Title Case a Sentence #25

Open sophielevens opened 7 years ago

sophielevens commented 7 years ago

Hello,

So I'm beginning to understand things a little bit more! :sparkles:

This one is beginning to annoy me though. It's just returning "I'm a little tea pot" which is about as annoying as when you order a pot of tea and it has just one cup's worth in it. :tea:

Thanks in advance!

QUESTION

Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.

For the purpose of this exercise, you should also capitalize connecting words like "the" and "of".

Remember to use Read-Search-Ask if you get stuck. Write your own code.

MY CODE


function toUpperCase(str) {

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

  for (var i = 0; i < str.length; i++) {
    str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);

  return str.join (" ");
}
}

titleCase("I'm a little tea pot");
curioustushar commented 7 years ago

Code

String.prototype.initCap = function () {
   return this.toLowerCase().replace(/(?:^|\s)[a-z]/g, function (m) {
      return m.toUpperCase();
   });
};

const str = "I'm a little tea pot";
str.initCap();

Reference

curioustushar commented 7 years ago

@sophielevens

Original Code

function toUpperCase(str) {
  str = str.toLowerCase().split(" ");
  for (var i = 0; i < str.length; i++) {
    str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
    return str.join(" "); // it should be outside the for loop
  }
 // function is not returning anything so it will not modify the original value 
}
titleCase("I'm a little tea pot");

Modified Code

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

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

Demo

jruts commented 7 years ago

Or a bit more functional:

const titleCase = input => input.split(' ')
  .map(word => word.charAt(0).toUpperCase() + word.slice(1))
  .join(' ');

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