regex target specific character around variable


I have this code:

var room = 'room2';
var exitroom = 'room1,room2,room3';

exitroom = exitroom.replace(/,${room},/,'');


you can try it here:

my expected output is simply room1,room3 by taking room2 out but since it may change its position within the string I want to target the , no matter if it comes before or after the string but I cant figure out the regex logic here. I know I could just do simply:

var room = 'room2';
var exitroom = 'room1,room2,room3';

exitroom = exitroom.replace(room+',','').replace(','+room,'');


which works but I think regex would be a more direct approach.

Thank you.

>Solution :

First, by writing .replace(/,${room},/,'') you are not using the variable room.

To use a variable in a regex you should call new RegExp()

Second, if you want a regex that will match when the comma is before or after the word, you can use a group () with an Or | operator.

so it should look like this:

var reg = new RegExp(`(?:${room},|,${room})`, "g");

The ?: at the beginning of the group, is just so it should be a non-capturing group, it should work just fine also without it

Leave a Reply