简体   繁体   中英

Including variable inside regex in Javascript

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.

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/'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM