How to use a variable within a regex in Javascript?

I have a regular expression and would like to put a variable inside it. How do I do?

My code is this:

public regexVariable(vRegex: string, testSentences: Array<any> ) {
    const regex = new RegExp('/^.*\b(' + vRegex + ')\b.*$/');
    const filterSentece = testSentences.filter(result => {
        if (regex.test(result)) {
            return result
        })
}

Upvotes: 0

Views: 1879

Answers (2)

Hashbrown
Hashbrown

Reputation: 13023

const regex = new RegExp(`^.*\\b(${vRegex})\\b.*$`);

You can use template literals (`, instead of "/') to build strings that you can interpolate expresions into; no more oldschool +ing.

The only thing that was an actual issue with your code, though, was the \b character class. This sequence is what you want RegExp to see, but you can't just write that, otherwise you're sending RegExp the backspace character.
You need to write \\b, which as you can see from that link, will make a string with a \ and an ordinary b for RegExp to interpret.

Upvotes: 2

Kosh
Kosh

Reputation: 18393

You're almost there, just look at RegEx constructor

const regex = new RegExp('^.*\\b(' + vRegex + ')\\b.*$');

Upvotes: 1

Related Questions