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?
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);
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"
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(", "));