Home > Software engineering >  JavasScript RegEx Replace Pattern in String that Looks Like An Array
JavasScript RegEx Replace Pattern in String that Looks Like An Array

Time:10-23

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?

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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"

CodePudding user response:

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(", "));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

What about this? Remove the delimiters [, ], > and <Tag: parts:

let s = "[<Tag: cats>, <Tag: dogs>, <Tag: parakeets>]";
s = s.replace(/[[\]>]|<.*? /g, "");
console.log(s);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Not using a regex but it does return the same result that need.

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

for ( let i = 0; i < s.length; i  ){
  let c = s[i]
  if ( c == '[' || c == ']' || c == '>')
    continue
  else if ( s.substr(i,5) == '<Tag:')
    i  = 5
  else
    res  = c
}
return res
  • Related