I want to write a for ... of loop where the first letter of the day is changed, in the array, to uppercase

0

I have my code, I just do not know how to end it ...

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

for (day of days) {
console.log(day);
}
    
asked by anonymous 19.09.2018 / 04:14

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 day.substr(1) returns the second character to the end. Then just concatenate both.

    
19.09.2018 / 04:28
1

Another interesting way to get 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));
}

Curiously, you can even do it with a simple regex, which takes the first letter and replaces it with the uppercase version at the cost of toUpperCase :

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

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

The% regex% is what picks up the first letter for the transformation.

    
19.09.2018 / 11:35