0

I have read this answer and I understand how to use the Regex constructor and have this this method numerous times before, but in this example I can't understand why the test() method does not return true. Please help! :-)

// This returns true
console.log(/HYD\./gi.test("HYD.,CYLINDER"))

// Now I will use a variable inside this test method so
// I have to use the Regex constructor

const abbreviation = "HYD.";

// I have to replace all "." with "\." to be compliant with the regex language.
const regex = new RegExp(`\\b${abbreviation.replace(".", "\\.")}\\b`, "gi");
console.log(regex)

// Now testing the regex constructor
console.log(regex.test("HYD.,CYLINDER"));
Isak La Fleur
  • 4,428
  • 7
  • 34
  • 50

1 Answers1

1

Your two regexes aren't the same. The one you're constructing, with \b "Word Boundary" markers, are causing your regex to fail.

This is because ., is not a word boundary.

Try with a literal /\bHYD\.\b/gi and you'll see it doesn't match either.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592