Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
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/

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!