October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Build a Cognitive Distortion Detector in Vanilla JavaScript

A practical vanilla JavaScript tutorial for matching a few transparent language patterns and presenting them as reflection prompts, not diagnoses.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can build a small cognitive-distortion detector with vanilla JavaScript by defining a handful of transparent text patterns, checking a user’s words against them, and offering reflection questions for any possible matches. Treat it as an educational prompt—not a diagnosis, a test of whether someone’s thoughts are objectively distorted, or a substitute for support from a mental-health professional. A matching phrase cannot tell you what a person means.

Set the detector’s limits before writing code

A phrase-matching tool can notice selected wording; it cannot reliably interpret context, tone, intent, or the facts behind a thought. “I always mess this up,” for example, could be a passing exaggeration, a quotation, or a belief the writer wants to examine. A rule match means only that the text contains a pattern you chose to look for.

Make that limitation visible in the interface. Use terms such as “possible pattern” and “reflection prompt,” not “diagnosis,” “detected distortion,” or a score that implies certainty. The NHS describes reframing as “catch it, check it, change it,” while emphasizing that there are no right or wrong answers and that a person may not be able to change a thought every time. NHS Every Mind Matters: Reframing unhelpful thoughts.

Choose a few patterns and prompts

Start with a small, inspectable set rather than trying to cover every possible thought pattern. The NHS uses accessible descriptions such as expecting the worst, focusing only on negatives, all-or-nothing thinking, and taking sole responsibility for negative events. An NHS training resource also lists technical labels including selective abstraction, over-generalisation, personalisation, emotional reasoning, discounting positives, mind reading, catastrophising, all-or-nothing thinking, and should/must statements. These are examples from different resources, not a single exhaustive or universally agreed taxonomy. NHS Every Mind Matters and Health Education England / NHS training material.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a first version, define each rule with a plain-language label, a brief description, patterns to check, and a question that leaves room for the user’s own interpretation:

const rules = [
  {
    id: "all-or-nothing",
    label: "All-or-nothing wording",
    description: "Language that may frame a situation in absolute terms.",
    patterns: [/b(always|never|everything|nothing)b/i],
    question: "Is there an exception, or a more specific way to describe what happened?"
  },
  {
    id: "worst-case",
    label: "Expecting the worst",
    description: "A thought that may focus on a feared outcome.",
    patterns: [/b(the worst|disaster|ruined)b/i],
    question: "What other outcomes are possible, and what evidence points to each one?"
  },
  {
    id: "should-must",
    label: "Should or must wording",
    description: "A thought framed as a strict rule or demand.",
    patterns: [/b(should|must|have to)b/i],
    question: "Where did this expectation come from, and is it realistic in this situation?"
  }
];

These starter patterns are deliberately simple examples, not clinically validated rules. They will miss many ways of expressing the same idea and may match harmless uses. For example, “I should call my sister” may be a practical reminder, not an unhelpful thought. Add a pattern only when you can explain why it is present and what useful, non-judgmental question it should prompt.

Match the text with native JavaScript

Regular expressions are built into JavaScript and can be used through RegExp and string methods; no framework or package is needed for this prototype. MDN: Regular expressions.

Keep matching separate from presentation. This function returns rules with at least one matching pattern; it does not claim that the thought fits a category:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function findPossiblePatterns(text, rules) {
  const normalizedText = text.toLowerCase();

  return rules.filter((rule) =>
    rule.patterns.some((pattern) => pattern.test(normalizedText))
  );
}

The example patterns are case-insensitive, and the input is lowercased consistently before matching. If you later use regular expressions with stateful flags such as g or y, repeated calls to test() can behave unexpectedly because those expressions keep an index; omit those flags for this simple matching use case.

Render possible matches accessibly

Give users a text area, a button, and a results region that assistive technology can detect when its contents change. Keep the result wording tentative and make it clear that no match is not a verdict about the text.

<label for="thought">Write a thought you want to explore</label>
<textarea id="thought" rows="5"></textarea>
<button id="check" type="button">Show reflection prompts</button>
<div id="results" aria-live="polite"></div>

<script>
  const thoughtInput = document.querySelector("#thought");
  const results = document.querySelector("#results");

  document.querySelector("#check").addEventListener("click", () => {
    const matches = findPossiblePatterns(thoughtInput.value, rules);
    results.replaceChildren();

    const intro = document.createElement("p");
    intro.textContent = matches.length
      ? "These wording patterns may be worth reflecting on. They are not conclusions about your thought:"
      : "No selected wording patterns matched. That does not determine whether the thought is helpful or unhelpful.";
    results.append(intro);

    for (const rule of matches) {
      const section = document.createElement("section");
      const heading = document.createElement("h2");
      heading.textContent = rule.label;
      const explanation = document.createElement("p");
      explanation.textContent = rule.description;
      const prompt = document.createElement("p");
      prompt.textContent = rule.question;
      section.append(heading, explanation, prompt);
      results.append(section);
    }
  });
</script>

Using textContent rather than inserting user input as HTML keeps the displayed results from interpreting typed text as markup. The live region announces updates; labels connect the text area to its instruction. If multiple rules match, show each as a possible prompt rather than ranking them or suggesting that more matches mean a more serious problem.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Make the prompts useful, not prescriptive

A detector should help someone examine a thought, not force a positive replacement. NHS Every Mind Matters suggests checking evidence and considering other explanations. Its thought record offers seven prompts: the situation; initial feelings; unhelpful thoughts; evidence supporting them; evidence against them; an alternative, more realistic or neutral thought; and how the person feels afterward. It can be completed mentally, in writing, in an app, or in an electronic or printed document. NHS Every Mind Matters: Thought record.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Useful follow-up questions include:

  • What evidence supports this thought?
  • What evidence points another way?
  • Are there other possible explanations or outcomes?
  • What would you say to a friend thinking this?

Let the user decide whether a question fits. A realistic or neutral alternative can be more useful than insisting on a positive one.

Test the rules for misleading matches

Before expanding the rule list, try each pattern against examples that should match and examples that should not. Include wording in a quotation, a negation, a practical reminder, and a sentence where the same keyword has a different meaning. Inspect what appears in the result and revise the pattern or its explanation if it invites an overconfident interpretation.

  • Explainability: simple phrases and regular expressions are easy to inspect and amend, but they cover only the wording you anticipated.
  • Broader wording coverage: adding more patterns may catch more variations, but also creates more opportunities for harmless or quoted language to match.
  • Response design: a gentle question makes a possible match an invitation to reflect; a definitive label can misrepresent what a text rule knows.

These are engineering trade-offs, not measured accuracy rankings. The cited sources establish JavaScript regular expressions as a language feature and describe thought-record and reframing exercises; they do not validate this detector or establish performance figures.

Keep the prototype in its proper role

The NHS describes CBT as a talking therapy involving changes in thinking and actions; sessions can include questioning unhelpful thoughts and considering other perspectives. A small browser tool can borrow the structure of reflection prompts, but it cannot provide that therapeutic relationship or replace professional support. NHS: Cognitive behavioural therapy (CBT).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.