I want to write a loop for...of which changes the first letter of the day, in the array, to uppercase

Asked

Viewed 47 times

0

I have my code, I just don’t know how to finish it...

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

for (day of days) {
console.log(day);
}
  • https://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript

2 answers

3

If you just want to print, you can use .toUpperCase() and .substr():

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

for (day of days) {
   console.log(day[0].toUpperCase()+day.substr(1));
}

The day[0].toUpperCase() converts the first letter to uppercase, and the day.substr(1) returns the second character to the end. Then just concatenate the two things.

  • Oops, I fell into the originally presented misleading to title vs code. The answer I removed was based on the susbstring(), could also be the slice(). How would the treatment be in case the element is an Empty string or even a null?

  • We wrote basically the same thing I would just trade the day[o] for substring(0,1) or substr(0,1). This is not the case for the array presented in the question, but because it is a generic string array, some of the elements may be empty or ""

  • Oh yes... then I’d just do an IF: if(day) console.log(day[0].toUpperCase()+day.substr(1));

  • no, it’s the same thing only the edita pro substr(0,1) in place of day[0] because it will not burst error in the case of a ["banana","","maçã"]. Sack?

  • No need, the question does not address this possibility.

1

Another interesting way to achieve the same result is with toUpperCase and slice. The slice serves to get the rest of the string without catching the first letter:

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

for (day of days) {
  console.log(day[0].toUpperCase() + day.slice(1));
}

Interestingly, he can even do it with a simple regex, which picks up the first letter and replaces it with a capital version at the expense of toUpperCase:

const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

for (day of days) {
  console.log(day.replace(/\w/, letra => letra.toUpperCase()));
}

The \w of the regex is the one that takes the first letter for processing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.