Creating Dynamic RegExp Objects

The task is to match a character that changes in every iteration of the loop using the following regular expression.

let regexp = new RegExp("" + [^char] + "");

The problem is, when I run the code, I get the following error: SyntaxError: Unexpected token ^.

How to fix this?

this is an array, ^ is not an allowed character in an array or variable name. Remember that you are creating a string, that string will become the regular expression because of the new RegExp

how do you create a string in which you need to add a variable?

let regexp = new RegExp(’’+ [’^char’] + ‘’);
var s = “char”;
console.log(s.match(regexp));
Tried the above and it works.:slight_smile:

but char is a variable, as far as I understand

Yes, char is a variable. So, how do I make it work then?

do you know how to concatenate a variable to a string? (like Word Blanks challenge)
knowing that whatever need to stay the same is the string(s) and char is the variable

1 Like

Ok, this worked: let regexp = new RegExp("[^" + [char] + "]");

you don’t need to create this array - there is any sense in putting your variable in an array you don’t use?
you can just do + char +

Yea, I changed that. Thanks for the explanation.