Spot the bug - #116: Text Search Result

Help me catch this sneaky regex bug.

function findLostPearls(text) {
  const pearlRegex = new RegExp("\bpearl(s)?\b", "g");
  return text.match(pearlRegex);
}
const treasureMap = "Many pearls scattered. A single pearl lies here. No perls!";
console.log(findLostPearls(treasureMap));

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

The interesting thing here is how \b gets interpreted.

Inside a string literal, it’s a backspace character, which is not what you want for a word boundary in regex. You need to escape the backslash for the RegExp constructor.

function findLostPearls(text) {
  const pearlRegex = new RegExp("\\bpearl(s)?\\b", "g");
  return text.match(pearlRegex);
}
const treasureMap = "Many pearls scattered. A single pearl lies here. No perls!";
console.log(findLostPearls(treasureMap));

Or, even simpler, use a regex literal directly:

function findLostPearls(text) {
  const pearlRegex = /\bpearl(s)?\b/g;
  return text.match(pearlRegex);
}
const treasureMap = "Many pearls scattered. A single pearl lies here. No perls!";
console.log(findLostPearls(treasureMap));

Spot the Bug answer: The regular expression uses an unescaped backslash for word boundaries, which is interpreted as an escape sequence rather than a regex metacharacter.

The fix:

Change `new RegExp("\bpearl(s)?\b", "g")` to `new RegExp("\\bpearl(s)?\\b", "g")` or use a regex literal: `/\bpearl(s)?\b/g`.

Why:
In JavaScript string literals, \b is interpreted as a backspace character. To represent a literal backslash that the regex engine can then interpret as a word boundary (\b), it needs to be escaped in the string, becoming \\b. Without this, the regex engine receives  (backspace) instead of \b (word boundary).

First-answer leaderboard

  1. @kirupa - 4 (firsts) :trophy:
  2. @adnanahmed - 2 (firsts)
  3. @emmawalter5 - 1 (first)

This is a classic. It’s like trying to tell your kid to draw a specific shape, but the crayon you gave them is actually a banana. The string parsing changes what you’re trying to do before the regex engine even sees it.

You’re right, the string parsing is the key here. The backslashes need to be escaped so the \b word boundary actually makes it to the regex engine.

You can fix it by changing the RegExp constructor to new RegExp("\\bpearl(s)?\\b", "g").