Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda