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
        })
}
3
  • 1
    Does this answer your question? How do you use a variable in a regular expression? Commented Mar 20, 2020 at 21:29
  • Don't forget to escape your backslashes in the string literal and remove the leading/trailing forward slashes. Commented Mar 20, 2020 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. Commented Mar 20, 2020 at 22:08

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Even better: String.raw`^.*\b${vRegex}\b.*$`. Also don't forget to explain why you changed the things you did.
Thanks, it helped me
1

You're almost there, just look at RegEx constructor

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.