0
votes

I have this ReGex string to catch anything that starts with go/ in a sentence:

/\bgo/i

It works great. However, the word go can change so I want to include a variable inside it so I moved it to RegExp like so:

const variable = 'go';
const rex = new RegExp(`/\b${variable}/`, 'i');`

However, it doesn't seem to work, I'm not sure why. I even tried removing the start/end sequence characters but it still doesn't work.

1
Try new RegExp(`\\b${variable}`, 'i');. - iz_

1 Answers

2
votes

I think you want this:

const rex = new RegExp(`\\b${variable}/`, 'i')

When using the RegExp constructor, you don't want to include the / at the start and end that would be on a literal regex like:

const rex = /foo/

Those / is just the regex literal syntax and not part of the regex content. Though you do seem to want an actual trailing /, so that stays.

Second, you have to double escape the backslash of \b as \\b. This is because in a normal string literal the backslash escapes the next character. In this case the b. But you want the backslash in your regex, so you have to escape the backslash, with a backslash.

const variable = 'go'
const rex = new RegExp(`\\b${variable}/`, 'i')
console.log('regex:', rex) // shows the regex that was created
console.log(rex.test('go/'))