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

105
Visualizações
JavasScript RegEx Replace Pattern in String that Looks Like An Array

I have an array in string-format. With Javascript, how to replace [, ], <Tag: , and > in the least amount of code possible:

let s = "[<Tag: cats>, <Tag: dogs>, <Tag: parakeets>]"

End result should look like:

"cats, dogs, parakeets"

This seems to work, but it's pretty... not great.

s.replace(/^\[/, '').replace(/\]$/, '').replaceAll('<Tag: ', '').replaceAll('>', '')

Is there a clever way to do this with RegEx?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Matching <Tag: and then capturing non-> characters looks like it'd do what you want:

const s = "[<Tag: cats>, <Tag: dogs>, <Tag: parakeets>]";
const result = s.replace(/<Tag: ([^>]+)>/g, '$1').replace(/[[\]]/g, '');
console.log(result);

Another approach, matching instead of replacing:

const s = "[<Tag: cats>, <Tag: dogs>, <Tag: parakeets>]";
const result = [...s.matchAll(/<Tag: ([^>]+)>/g)]
  .map(match => match[1])
  .join(', ');
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

I would suggest matching all substrings and joining them:

const result = [...s.matchAll(/<Tag:\s*(\w+)>/g)]
    .map(
        ([, m]) => m
    )
    .join(', ');


// result: "cats, dogs, parakeets"
about 4 years ago · Juan Pablo Isaza Relatório

0

When an infinite quantifier in a lookbehind is supported, you can match all the values between <Tag: and the > and make sure all the matches are between square brackets.

See the regex matches in this regex demo.

let s = "[<Tag: cats>, <Tag: dogs>, <Tag: parakeets>]"
const regex = /(?<=\[[^\][]*<Tag: )\w+(?=>[^\][]*\])/g;
console.log(s.match(regex).join(", "));

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