Active learning examples Question 2


Guys, I am stuck on this particular exercise. After several hours of try to figure out the question I decided to look click on the solution button but I still don’t get how they came up with the answer. I’ll be grateful if any one can help. Thanks


In this exercise we have the names of cities in the United Kingdom, but the capitalization is all messed up. We want you to change them so that they are all lower case, except for a capital first letter. A good way to do this is to:

  1. Convert the whole of the string contained in the input variable to lower case and store it in a new variable.
  2. Grab the first letter of the string in this new variable and store it in another variable.
  3. Using this latest variable as a substring, replace the first letter of the lowercase string with the first letter of the lowercase string changed to upper case. Store the result of this replace procedure in another new variable.
  4. Change the value of the result variable to equal to the final result, not the input .

const list = document.querySelector(’.output ul’);
list.innerHTML = ‘’;
let cities = [‘lonDon’, ‘ManCHESTer’, ‘BiRmiNGHAM’, ‘liVERpoOL’];

for (let i = 0; i < cities.length; i++) {
let input = cities[i];
let lower = input.toLowerCase();
let firstLetter = lower.slice(0,1);
let capitalized = lower.replace(firstLetter,firstLetter.toUpperCase());
let result = capitalized;
let listItem = document.createElement(‘li’);
listItem.textContent = result;
list.appendChild(listItem);

}

let us dive into it line by line

this retrieve a reference to the list using the same css selector way

this create array for the cities name

now let us jump into the loop

for (let i = 0; i < cities.length; i++) {    // this loop into each item of the array
let input = cities[i];                              // this create variable input and store the current element of the array at index i 
let lower = input.toLowerCase();      // this create new element called lower and use one of the js api methos to convert the string input to lower case
let firstLetter = lower.slice(0,1);             // this create variable firstletter and store the first letter of lower into it
let capitalized = lower.replace(firstLetter,firstLetter.toUpperCase());  // this create variable that called capitalized and use the replace from js api to replace the first accurance of the letter with upper case version of it
let result = capitalized;  // create variable result that equal the value of  capitalized
let listItem = document.createElement(‘li’);  //create li element 
listItem.textContent = result;                // set the text of the li item to be equal the value of result
list.appendChild(listItem);   this appened the li item we just created to the list element 

}

hope that help and have a nice day :slight_smile:

1 Like

Thanks @justsomeone, It’s clear now.

you welcome :slight_smile:

1 Like