I am using "[TITLE] [STORENAME] [DYNAMIC]".replace(regex, `$1|${replace}=${value}]`); multiple times but everytime before I use it, I change the variable replace. See the full code:
obj = {} || obj;
const replace = 'prefix';
let search = 'TITLE';
const value = 'MY VALUE';
const regex = new RegExp(`(\\[${search}(?:\\|[^\\][]*)?)]`, 'gi');
obj.str = "[TITLE] [STORENAME] [DYNAMIC]".replace(regex, `$1|${replace}=${value}]`);
search = 'STORENAME';
obj.str = "[TITLE] [STORENAME] [DYNAMIC]".replace(regex, `$1|${replace}=${value}]`);
search = 'DYNAMIC';
obj.str = "[TITLE] [STORENAME] [DYNAMIC]".replace(regex, `$1|${replace}=${value}]`);
console.log(obj.str);
So as you see I get the result [TITLE|prefix=MY VALUE] [STORENAME] [DYNAMIC] but the goal is to get this result: [TITLE|prefix=MY VALUE] [STORENAME|prefix=MY VALUE] [DYNAMIC|prefix=MY VALUE].
Probably it is because I use the same string for replace() all over again but I have also tried it this way:
obj = {} || obj;
obj.str = '[TITLE] [STORENAME] [DYNAMIC]';
const replace = 'prefix';
let search = 'TITLE';
const value = 'MY VALUE';
const regex = new RegExp(`(\\[${search}(?:\\|[^\\][]*)?)]`, 'gi');
obj.str = obj.str.replace(regex, `$1|${replace}=${value}]`);
search = 'STORENAME';
obj.str = obj.str.replace(regex, `$1|${replace}=${value}]`);
search = 'DYNAMIC';
obj.str = obj.str.replace(regex, `$1|${replace}=${value}]`);
console.log(obj.str);
But the output is still not correct.
const regex = new RegExp((\[${search}(?:\\|[^\][]*)?)], 'gi');runs it is set in stone... It will not update when you change the variable