Custom Regex using Variable

I am working on a program that requires me to use a variable in the regex.

The idea is of follows:

let l1 = "A"
let l2 = "B"
let reg = `/(${l1}|${l2})/`
let regex = new RegExp(reg, 'i')
console.log(regex.test("A"))

I can put any value for l1 and l2 and be able to make a regex that can test for those letters. However, this always returns false.

The regex built with the assignment operator, do not allow variables.
The regex built with the constructor do allow them.

Instead of declaring a literal reg… Make a string, your string can be built with variables, then use the RegExp constructor and pass the string

> let l1 = 'A'
> let l2 = 'B'
> let str = l1 + '|' + l2
> let reg = new RegExp(str)
> reg.test('A')
true
2 Likes