-1

I am making my debut with coding and i got stuck with a problem. I have to turn the First letter of a string toUpperCase. Can someone please guide me ? e.g : the quick fox ---> The Quick Fox.

here is my code :

function convertFirstLetterOfWordsToUpperCase(phrase){
    phrase = phrase.split("");
    console.log(mot);
    phrase[0] = phrase[0].toUpperCase();
    for(var i = 1; i <= phrase.length; i++){
     if(phrase[i] == ""){
      i++;
      phrase[i] = phrase[i].toUpperCase();
     }
    }
    phrase = phrase.join("");
    console.log(mot);
}
convertFirstLetterOfWordsToUpperCase("the quick fox");

here is the display : The quick fox.
Thanks for the help.

YakovL
  • 7,557
  • 12
  • 62
  • 102
Lobe Loic
  • 21
  • 5
  • What is `mot` ? – Nick Parsons Jul 06 '19 at 13:45
  • Well, if you want to show it in UI then would be better to use css `text-transform`, if it's needed in code for some reason, then use `slice` to split the string on 2 parts and then concatenate it back using `toUpperCase` on the first part. You can't change strings in JavaScript, they are immutable, you have to create a new string each time. – Dmitriy Jul 06 '19 at 13:47
  • Welcome to Stack Overflow! Please take the [tour] (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) I also recommend Jon Skeet's [Writing the Perfect Question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/). Please [**search**](/search?q=%5Bjs%5D+capitalize+word) before posting. More about searching [here](/help/searching). – T.J. Crowder Jul 06 '19 at 13:52
  • the main problem is that you aren't `return`ing anything form the function. Try `return phrase` at the bottom of it – Robin Zigmond Jul 06 '19 at 13:53

2 Answers2

0

Your issue is that you're trying to detect spaces in between your words using:

if (phrase[i] == "") {

But instead, when you split based on "", your spaces are not empty strings, they are strings with spaces (" "), and so you should check against that instead:

if (phrase[i] === " ") {

See example below:

function convertFirstLetterOfWordsToUpperCase(phrase) {
  phrase = phrase.split("");
  phrase[0] = phrase[0].toUpperCase();
  for (var i = 1; i <= phrase.length; i++) {
    if (phrase[i] === " ") {
      i++;
      phrase[i] = phrase[i].toUpperCase();
    }
  }
  return phrase.join("");
}
console.log(convertFirstLetterOfWordsToUpperCase("the quick fox"));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

You can try with css or javascript as follows :

function capitalize(string) {
    return string.replace(/\w\S*/g, function(text){
        return text.charAt(0).toUpperCase() + text.substr(1).toLowerCase();
    });
}
FZs
  • 16,581
  • 13
  • 41
  • 50