regex target specific character around variable

Advertisements

Hi,

I have this code:

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

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

console.log(exitroom);

you can try it here: https://jsfiddle.net/uq9w0Ls4/

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,'');

console.log(exitroom);

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");
exitroom.replace(reg,'');

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 ReplyCancel reply