Search code examples
javascripthtmlstringcharactervar

I had to use a for loop to to go through each character in a string but the code is not working properly


These are the instruction for the exercise I am supposed to do: Start with a prompt that asks the user to enter any string.

Using a for loop, go through each character in the string.

If the string contains the letter A (capital or lowercase), break out of the loop and print the message below to the screen.

If the string does not contain the letter A, print the message below to the screen.

Here is my code

var text= prompt("Enter any string.")
for (var i = 0; i < text.length; i++) {
    if (text[i] === "A")
    {alert("The string contains the letter A.");
}
     if (text[i] === "a")
    {alert("The string contains the letter A.");
}
 else
      {alert("The string does not contain the letter A.");
}
}

Solution

  • Why do you need loop to do so, you can do it by this

    if(text.includes('A')){
        alert("The string contains the letter A.");
    }else if(text.includes('a')){
        alert("The string contains the letter a.");
    }else{
        alert("The string does not contain the letter A.");
    }
    

    UPDATE

    var text= prompt("Enter any string.")
    var letterA = false;
    var lettera = false
    for (var i = 0; i < text.length; i++) {
        if (text[i] === "A")
        {
            letterA = true;
        }
        if (text[i] === "a")
        {
            lettera = true
        }
    }
    if(letterA=== true){
        alert('string contains letter A');
    }else if(lettera ===true){
        alert('string contains letter a');
    }else{
         alert(' string does not contain a or A character');
    }