'Inserting a variable string inside my regex is not working in javascript [NOT a duplicate]

Hi,

I have this code:

var regcat = /\b(aa1)[a-z]\d+[.][g][i][f]\b/;
var testit = "aa1a2.gif";

console.log(regcat.test(testit));

it produces TRUE as expected but I want to replace the "a1" part with a variable:

var catvar = "a1";
var regcat = "/\b(a"+catvar+")[a-z]\d+[.][g][i][f]\b/";
var testit = "aa1a2.gif";

console.log(regcat.test(testit));

didnt work so I tried the suggestions in old questions like this:

var catvar = "a1";
var regcat = RegExp("/\b(a"+catvar+")[a-z]\d+[.][g][i][f]\b/","g");
var testit = "aa1a2.gif";

console.log(regcat.test(testit));

but nothing works. What am I doing wrong? You can see it here: https://jsfiddle.net/haL62ejp/

Thank you.

PS: Its really FRUSTRATING to have my questions closed by people who WONT EVEN READ them. I had already checked the suggested questions before opening mine:

How do you use a variable in a regular expression? (23 answers) Use dynamic (variable) string as regex pattern in JavaScript (8 answers)

tried the answers there and still DIDNT WORK so thats why I posted this question so keep that in mind before closing it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source