Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

regex target specific character around variable

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/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading