0

I have found so many similar questions, but after much effort I can not nail down what I am missing. I want to find the exact match of a word within a string where both the word and the string are variables AND there are modifiers inside the regex. Here is what I think it should look like:

const string = "This is my longer string";
const word = "is";
const wordRegEx = `\b${word}\b`;
const regExPattern = new RegExp(wordRegEx);
if (string.match(regExPattern)) console.log('passed:', word, string); //should not return 'This'
tmurv
  • 60
  • 6
  • 1
    Use ``const wordRegEx = `\\b${word}\\b`;``. Or, ``const wordRegEx = String.raw`\b${word}\b`;`` – Wiktor Stribiżew Apr 12 '20 at 15:22
  • Thank you! I had tried escaping the \b so many times, it took the String.raw to work. That is a new method to me. Finally I see 'passed'! – tmurv Apr 12 '20 at 15:34

0 Answers0