I have a string that looks like this: [TITLE|prefix=a].
From that string, the text |prefix=a is dynamic. So it could be anything or empty. I would like to replace (in that case) [TITLE|prefix=a] with [TITLE|prefix=a|suffix=z].
So the idea is to replace ] from a string that starts with [TITLE with |suffix=z].
For instance, if the string is [TITLE|prefix=a], it should be replaced with [TITLE|prefix=a|suffix=z]. If it's [TITLE], it should be replaced with [TITLE|suffix=z] and so on.
How can I do this with RegEx?
I have tried it this way but it gives an error:
let str = 'Lorem ipsum [TITLE|prefix=a] dolor [sit] amet [consectetur]';
const x = 'TITLE';
const regex = new RegExp(`([${x})*]`, 'gi');
str = str.replace(regex, "$1|suffix=z]");
console.log(str);
I have also tried to escape the characters [ and ] with new RegExp(`(\[${x})*\]`, 'gi'); but that didn't help.