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

103
Views
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 answers
Answer question

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 Report

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 Report

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 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!