Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Loops and Text

In the lesson on arrays, you saw that text isn't an array, but it has a .length, and you can read its characters by index: word[0] is the first character. That is all a loop needs, so you can go through text character by character, just like through an array:

const word = "Hello";
for (let i = 0; i < word.length; i++) {
    console.log(word[i]);
}

This prints:

H
e
l
l
o

The for...of loop works with text too. In each iteration, the variable holds the next character:

const word = "Hello";
for (const character of word) {
    console.log(character);
}
H
e
l
l
o

The patterns from the previous exercises work with text as well. This loop counts the letters l:

const word = "Hello";
let count = 0;
for (const character of word) {
    if (character === "l") {
        count++;
    }
}
console.log("Number of l:", count);
Number of l: 2

Remember that uppercase and lowercase letters are different characters: "H" === "h" is false.

Instructions

  1. 1

    Go through text with a loop and print each of its characters on its own line.

  2. 2

    Below that, count how many times the letter r appears in text: create a variable count with the value 0, go through the text again and increase count by one for every r. After the loop, print console.log("Number of r:", count);. The output is Number of r: 2.

Back

10/12

  1. 1. The while Loop
  2. 2. Shorter Notation
  3. 3. The for Loop
  4. 4. Looping Through Arrays
  5. 5. Sum and Average
  6. 6. Counting
  7. 7. The Largest Value
  8. 8. The break Statement
  9. 9. The continue Statement
  10. 10. Loops and Text
  11. 11. Nested Loops
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.