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

102
Visualizações
Stop user from inputting letters into html input tag based on variable

I am trying to make a word game where the user gets a string of 8 letters and they must make as many words as they can out of them. I am trying to make it so that they can only type the letters from the 8 letter string. I am having trouble making it so that it blocks the letters based on the variable which is the 8 letter string.

Here is my code:

// Choosing random letters for game (3 vowels, 5 consonants)
function getRandomCharsFromString(str, length) {
  return Array.from({
    length
  }, () => {
    return str[Math.floor(Math.random() * str.length)]
  });
}

function shuffle(str) {
  var a = str.split(""),
    n = a.length;

  for (var i = n - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a.join("");
}

function getRandomString() {
  var vowels = 'aeiou';
  var consonants = 'bcdfghjklmnpqrstvwxyz';

  var randomVowels = getRandomCharsFromString(vowels, 3);
  var randomConsonants = getRandomCharsFromString(consonants, 5);

  var randomWord = [...randomVowels, ...randomConsonants].join('')
  return shuffle(randomWord)
}

//Setting the letter variable to nothing
var letters = "";

//Showing letters generated in the gameplay interface
function newGame() {
  words = 0;
  document.querySelector('.gameplay').style.display = 'flex';
  letters = getRandomString();
  document.querySelector('#wordcount').innerHTML = `${words} `;
  document.querySelector('#gameletters').innerHTML = `${letters}`;
  console.log(letters);
}

//Preventing player from using letters that aren't in the word
function keyPressed(e) {
  console.log(e.key);
  if (e.key == `${letters}`) {
    return true;
  } else {
    return false;
  }
}

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Right here

if (e.key == `${letters}`) {

This tests if the key pressed, in e.key is equal to the string letters, which it will never be.

There are a couple of other ways you could test.

if (letters.indexOf(e.key) > -1) {
    return true;
}
else {
    return false;
}
// or
if (letters.includes(e.key)) {
    return true;
}
else {
    return false;
}

Anything that returns true else returns false can be shortened to just return the results of the test:

return (letters.includes(e.key));

Another way would be to turn the letters string into an array and use .includes() — but really only if you have some other reason to want an array.

return letters.split('').includes(e.key);
about 4 years ago · Juan Pablo Isaza Relatório

0

The key event property is going to be a single character/letter. Your 8-character string is not going to equate to just one. You have a number of quick-to-implement options. Here's my suggested update, assuming you are attaching keyPressed to the keypress event handler:

function keyPressed(e) {
    console.log(e.key);
    if (letters.includes(e.key)) {
        return true;
    }
    else {
        return false;
    }
}

Or, a slightly more compressed version:

function keyPressed(e) {
    return letters.includes(e.key);
}
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