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 emp
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]
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);