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
JavaScript
x
13
13
1
var text= prompt("Enter any string.")
2
for (var i = 0; i < text.length; i++) {
3
if (text[i] === "A")
4
{alert("The string contains the letter A.");
5
}
6
if (text[i] === "a")
7
{alert("The string contains the letter A.");
8
}
9
else
10
{alert("The string does not contain the letter A.");
11
}
12
}
13
Advertisement
Answer
Why do you need loop to do so, you can do it by this
JavaScript
1
8
1
if(text.includes('A')){
2
alert("The string contains the letter A.");
3
}else if(text.includes('a')){
4
alert("The string contains the letter a.");
5
}else{
6
alert("The string does not contain the letter A.");
7
}
8
UPDATE
JavaScript
1
21
21
1
var text= prompt("Enter any string.")
2
var letterA = false;
3
var lettera = false
4
for (var i = 0; i < text.length; i++) {
5
if (text[i] === "A")
6
{
7
letterA = true;
8
}
9
if (text[i] === "a")
10
{
11
lettera = true
12
}
13
}
14
if(letterA=== true){
15
alert('string contains letter A');
16
}else if(lettera ===true){
17
alert('string contains letter a');
18
}else{
19
alert(' string does not contain a or A character');
20
}
21