Reputation: 133
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.
Upvotes: 3
Views: 79
Reputation: 627468
You need to remember to use \\
in a regular string literal to define a single literal backslash.
Then, you need a pattern like
/(\[TITLE(?:\|[^\][]*)?)]/gi
See the regex demo. Details:
(\[TITLE\|[^\][]*)
- Capturing group 1:
\[TITLE
- [TITLE
text(?:\|[^\][]*)?
- an optional occurrence of a |
char followed with 0 or more chars other than ]
and [
]
- a ]
char.Inside your JavaScript code, use the following to define the dynamic pattern:
const regex = new RegExp(`(\\[${x}\\|[^\\][]*)]`, 'gi');
See JS demo:
let str = 'Lorem ipsum [TITLE|prefix=a] dolor [sit] amet [consectetur] [TITLE]';
const x = 'TITLE';
const regex = new RegExp(`(\\[${x}(?:\\|[^\\][]*)?)]`, 'gi');
str = str.replace(regex, "$1|suffix=z]");
console.log(str);
// => Lorem ipsum [TITLE|prefix=a|suffix=z] dolor [sit] amet [consectetur]
Upvotes: 2
Reputation: 614
I think the solution to your problem would look similar to this:
let str = 'Lorem ipsum [TITLE|prefix=a] dolor [sit] amet [consectetur]';
str = str.replace(/(\[[^\|\]]+)(\|[^\]]*)?\]/g, "$1$2|suffix=z]");
console.log(str);
Upvotes: 0