5 letter word list

by Ben Gillbanks

HTML

<div id="letterInputs"></div>
  <button onclick="findWords()">Find Words</button>
  <h2>Possible Words:</h2>
  <ul id="wordList"></ul>

CSS

#letterInputs {
    margin-bottom: 1em;
}
#letterInputs input {
    width: 1em;
    margin: 0.1em;
    padding: 0.2em;
}

JavaScript

const fiveLetterWords = [
      "apple",
      "table",
      "chase",
      "blank",
      "peach",
      "snake",
      "lemon",
      // Add more words as needed
    ];

    function createLetterInput() {
      const input = document.createElement("input");
      input.setAttribute("type", "text");
      input.setAttribute('placeholder', '?');
      input.setAttribute("maxlength", "1");
      return input;
    }

    function initializeInputs() {
      const letterInputs = document.getElementById("letterInputs");
      for (let i = 0; i < 5; i++) {
        const input = createLetterInput();
        letterInputs.appendChild(input);
      }
    }

    function findWords() {
      const wordList = document.getElementById("wordList");
      wordList.innerHTML = "";

      let pattern = "";
      const letterInputs = document.querySelectorAll("#letterInputs input");
      for (const input of letterInputs) {
        const letter = input.value.toLowerCase();
        if (letter === "" || letter === "?") {
          pattern += "?";
        } else {
          pattern += letter;
        }
      }

      if (!isValidPattern(pattern)) {
        alert("Please enter a valid letter pattern.");
        return;
      }

      const matchingWords = findMatchingWords(pattern);

      if (matchingWords.length === 0) {
        wordList.innerHTML = "<li>No matching words found</li>";
      } else {
        matchingWords.forEach((word) => {
          const listItem = document.createElement("li");
          listItem.textContent = word;
          wordList.appendChild(listItem);
        });
      }
    }

    function isValidPattern(pattern) {
      const patternRegex = /^[a-z?]{5}$/;
      return patternRegex.test(pattern);
    }

    function findMatchingWords(pattern) {
      const regex = new RegExp("^" + pattern.replace(/\?/g, "[a-z]") + "$");
      return fiveLetterWords.filter((word) => regex.test(word));
    }

    initializeInputs();