0

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
        })
}
madtyn
  • 1,129
  • 20
  • 43
  • 1
    Does this answer your question? [How do you use a variable in a regular expression?](https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression) – ggorlen Mar 20 '20 at 21:29
  • Don't forget to escape your backslashes in the string literal and remove the leading/trailing forward slashes. – ggorlen Mar 20 '20 at 21:37
  • A word of caution The '.*' at the beginning of the regex may not be what you intend it to be. As Regexes are greedy by default it has a high chance of capturing to much. So if you run in any problems try using '.*?' instead of '.*' to get non greedy behaviour. – Andreas Neumann Mar 20 '20 at 22:08

2 Answers2

1

You're almost there, just look at RegEx constructor

const regex = new RegExp('^.*\\b(' + vRegex + ')\\b.*$');
Kosh
  • 14,657
  • 2
  • 15
  • 31
1
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.

Hashbrown
  • 8,877
  • 7
  • 57
  • 71