Spot the bug - #188: Textbox

Tiny regex quest hides a subtle flaw.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>Spot the Bug: Regex Edition</title>
  <style>
    body { font-family: sans-serif; padding: 1rem; }
    .box { border: 1px solid #ccc; padding: 1rem; width: 320px; }
    input { width: 100%; padding: .25rem; }
    .result { margin-top: .5rem; font-family: monospace; }
  </style>
</head>
<body>
  <div class="box">
    <label>Enter a simple alphanumeric string (letters or digits only):</label>
    <input id="inp" type="text" />
    <div class="result" id="out"></div>
  </div>
  <script>
    const input = document.getElementById('inp');
    const out = document.getElementById('out');
    // Bug: the regex uses a capturing group but the test ignores it; also
    // the pattern mistakenly allows spaces due to an incorrect flag setup.
    const regex = /^(?:[A-Za-z0-9]+)\s*$/; // intended: without spaces
    input.addEventListener('input', function() {
      const value = input.value;
      if (regex.test(value)) {
        out.textContent = 'VALID: ' + value;
      } else {
        out.textContent = 'INVALID: ' + value;
      }
    });
  </script>
</body>
</html>

Reply with what is broken and how you would fix it.

Spot the Bug answer: Regex incorrectly allows trailing spaces due to \s* and the comment mentions a capturing group

The fix:

const regex = /^(?:[A-Za-z0-9]+)$/; // remove the \s* to disallow spaces

Why:
The requirement is letters or digits only with no spaces. The original pattern allowed spaces because of the optional whitespace (\s*) at end, making inputs with spaces appear valid; removing it enforces the intended constraint.

First-answer leaderboard

  1. @emmawalter5 - 15 (firsts) :trophy:
  2. @Apexcodes - 9 (firsts)
  3. @kirupa - 8 (firsts)
  4. @PipMuse - 5 (firsts)
  5. @adnanahmed - 2 (firsts)

Nice catch — the \s* is exactly the culprit, and your fix is the clean one. Dropping it makes the pattern match what the label actually says: letters and digits, full stop, no trailing spaces sneaking through as VALID.

One small footnote: the comment’s capturing-group line is a red herring — (?:…) is already non-capturing, so that part was never the problem. The whole bug really was just that one little \s*.