0

I'm writing a bot for discord and using this project to teach myself javascript. I have a predefined string set to message variable and I want this to script to change the first letter of each word in the string to a capital, but so far the function is only returning the message as it was spelt. I cannot understand why

var string = message.substr(message.indexOf(" ")+1);

function capital_letter(str)
        {   
            str=str.split(" ");

            for (var i = 0, x = str.length; i<x, i++;) 
            {
                str[i] =     str[i].charAt(0).toUpperCase() + str[i].substr(1);
            };

        return str.join(" ");};

If message = "ring of life" I would expect the output to be "Ring Of Life"

Richard Goodman
  • 101
  • 1
  • 1
  • 8
  • 1
    Review your `for` loop, you make a mistake using a `,` where a `;` should be. The loop should be defined like: `for (var i = 0, x = str.length; i < x; i++)` or even better `for (var i = 0; i < str.length; i++)` – Shidersz Jul 12 '19 at 21:34

2 Answers2

0

you can try this.

str.toLowerCase().replace(/\b\w{3,}/g, function (l) {
   return l.charAt(0).toUpperCase() + l.slice(1);
});
Megh
  • 135
  • 2
  • 10
0

You had some syntax errors, here's a corrected version of your captial_letter function:

function capital_letter (str) {
  str = str.split(' ')
  for (var i = 0; i < str.length; i++) {
    const firstChar = str[i].charAt(0)
    str[i] = firstChar.toUpperCase() + str[i].substr(1)
  };

  return str.join(' ')
};

The biggest one was to separate your loop parameters using ; instead of ,:

for (var i = 0; i < str.length; i++) 

p.s. looks like you might benefit from a better IDE :-)

Will Jenkins
  • 9,507
  • 1
  • 27
  • 46