Preloader
Others
  • Estimated reading time: 4 Minutes

How to Build a Five-Letter Word Filter in JavaScript

How to Build a Five-Letter Word Filter in JavaScript

A useful word finder does not need a prediction model or a database server. For a small dictionary, a few JavaScript predicates can turn letter clues into a manageable list of candidates. The tricky part is defining what each clue means, especially when a letter appears more than once.

This tutorial builds a browser-friendly filter for five-letter English words. It supports fixed positions, required letters, excluded letters, prefixes, and suffixes. The examples use a small demonstration list so you can inspect every result.

Start with a consistent dictionary

Keep the search data separate from the interface. Normalize it once rather than trimming, uppercasing, and deduplicating the same entries on every keystroke.

const sampleWords = [
  "apple", "apply", "ample", "angle", "alert",
  "alter", "later", "plate", "pleat", "petal",
  "crane", "slate", "stare", "stone", "level",
  "eerie", "civic", " APPLE ", "four", "abc12"
];

function normalizeDictionary(entries) {
  return [...new Set(
    entries
      .filter((entry) => typeof entry === "string")
      .map((entry) => entry.trim().toUpperCase())
      .filter((entry) => /^[A-Z]{5}$/.test(entry))
  )];
}

const dictionary = normalizeDictionary(sampleWords);

The regular expression deliberately limits this example to five ASCII letters. An accented-word or multilingual dictionary needs a different definition of a letter; changing the character-count check alone is not sufficient.

For a production list, check its license, spelling variants, and inclusion rules. A broad English dictionary is not automatically a list of accepted guesses for a particular game, and accepted guesses are not necessarily possible daily answers.

Define required-letter counts

Suppose a user enters PP in a required-letters field. Checking word.includes("P") twice would incorrectly accept AMPLE, which contains only one P. Count occurrences instead.

function countLetters(text) {
  const counts = new Map();
  for (const letter of text) {
    counts.set(letter, (counts.get(letter) ?? 0) + 1);
  }
  return counts;
}

In this tutorial, required letters specify minimum total counts in the candidate. A fixed P and one P in the required field describe the same occurrence, unless the required field explicitly contains PP. Define this behavior beside the input so users do not have to guess.

Combine the constraints

Use a five-character pattern with ? for unknown positions. Keep the other fields as plain letter strings. This version rejects invalid input instead of silently converting a typo into a different search.

function findWords(words, options = {}) {
  const {
    pattern = "?????",
    required = "",
    excluded = "",
    prefix = "",
    suffix = ""
  } = options;

  const p = pattern.trim().toUpperCase();
  const req = required.trim().toUpperCase();
  const exc = excluded.trim().toUpperCase();
  const pre = prefix.trim().toUpperCase();
  const suf = suffix.trim().toUpperCase();

  if (!/^[A-Z?]{5}$/.test(p)) {
    throw new Error("Use five letters or ? placeholders for the pattern.");
  }
  if (![req, exc].every((value) => /^[A-Z]*$/.test(value))) {
    throw new Error("Required and excluded fields accept letters only.");
  }
  if (![pre, suf].every((value) => /^[A-Z]{0,5}$/.test(value))) {
    throw new Error("Prefixes and suffixes accept up to five letters.");
  }

  const minimumCounts = countLetters(req);
  const excludedLetters = new Set(exc);

  return words.filter((word) => {
    if ([...p].some((letter, i) => letter !== "?" && word[i] !== letter)) {
      return false;
    }
    if ([...word].some((letter) => excludedLetters.has(letter))) {
      return false;
    }
    if (!word.startsWith(pre) || !word.endsWith(suf)) {
      return false;
    }

    const available = countLetters(word);
    return [...minimumCounts].every(
      ([letter, minimum]) => (available.get(letter) ?? 0) >= minimum
    );
  });
}

The function expects the normalized dictionary created earlier. Each condition removes candidates that cannot satisfy the clues. The remaining entries keep their original order: filtering does not make them more common, more likely, or better guesses.

JavaScript's Array.prototype.filter() returns a new array containing entries that pass the callback. Empty prefixes and suffixes need no special branch because startsWith() and endsWith() match an empty string.

Check the output before building the interface

Run a few cases with results you can verify by hand:

console.log(findWords(dictionary, { pattern: "A??LE" }));
// ["APPLE", "AMPLE", "ANGLE"]

console.log(findWords(dictionary, { required: "PP" }));
// ["APPLE", "APPLY"]

console.log(findWords(dictionary, {
  pattern: "A??LE",
  excluded: "P"
}));
// ["ANGLE"]

console.log(findWords(dictionary, { prefix: "ST", suffix: "E" }));
// ["STARE", "STONE"]

console.log(findWords(dictionary, { required: "EE" }));
// ["LEVEL", "EERIE"]

Also test contradictory input. A fixed A combined with an excluded A must return no matches. In the interface, show an explanation of the conflict rather than suggesting that the dictionary is missing words.

Turn the filter into a usable tool

Expose each constraint through a labeled input and show the match count beside the results. Keep a reset action visible, handle validation errors near the relevant field, and distinguish an empty result from an untouched search.

For a practical interface reference, this five-letter word filtering tool lets users combine known positions, required letters, exclusions, and prefix or suffix clues. The implementation here is an independent example, not its published source code.

For a modest list, begin with a direct scan and measure responsiveness on a phone before introducing indexes or Web Workers. Limit the number of result cards rendered at once; displaying thousands of buttons can become a separate cost from filtering the words.

Know where a general filter stops

This is a dictionary filter, not a complete Wordle solver. It does not track yellow-letter positions or maximum letter counts. In particular, a gray instance of a letter cannot always be treated as a global exclusion when another instance receives colored feedback.

A dedicated solver needs per-position exclusions, minimum and maximum occurrence counts, and a suitable game dictionary. Keeping those rules separate from the general filter makes the behavior easier to explain and test.

Start with explicit constraints and predictable results. A small tool that handles repeated letters correctly and explains its limits is more useful than one that promises to predict an answer its data cannot establish.

Weekly trending
Pachat Code Reviews Should Start With a Failing Test
30 Nov, 2026
  • Estimated reading time: 4 Minutes
A Software Vendor’s Guide to License Operations at Scale
30 Nov, 2026
  • Estimated reading time: 4 Minutes
How to Build a Five-Letter Word Filter in JavaScript
30 Nov, 2026
  • Estimated reading time: 4 Minutes
Our Sponsors

Our blog is proudly supported by industry-leading sponsors.