Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

266
Visualizações
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.");
}
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You are alerting every iteration of the loop, meaning that you're calling 'alert' for each letter.

What you likely want to do is make a variable like

var doesContainA = false;

Then in your loop, if it equals a or A, change doesContainA to true;

At the end, do one final if statement which controls which message to alert, based on if that variable became true or is still false

Also, formatters can help you read code easier by lining everything up, something like this

about 4 years ago · Juan Pablo Isaza Relatório

0

Use a separate function that returns a boolean result. This method lets you stop the iteration after first occurrence of desired letters:

function hasLetter(text) {
    var char;
    for (var i = 0; i < text.length; i++) {
        char = text[i];
        if (char === "A" || char === "a") {
            return true;
        }
    }

    return false;
}

var text = prompt("Enter any string.");

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

You can also use function String.toLowerCase and check whether the char matches lowercase letter 'a':

char = text[i].toLowerCase();
if (char === "a") {
    return true;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

EDIT: Since OP specifically wants to use a for loop.

  const str = "anything";
  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    if (char === "A") {
      console.log("contains A");
    } else if (char === "a") {
      console.log("contains a");
    } else {
      console.log("do something...");
    }
  }

Original Answer:

You can use includes method instead of a for loop.

  const str = "Anything";
  if (str.includes("A")) {
    console.log("contains A");
  } else if (str.includes("a")) {
    console.log("contains a");
  } else {
    console.log("do something...");
  }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda