const regex = /(?(DEFINE)
(?<nestedBrackets> \[ [^][]* (?:\g<nestedBrackets>[^][]*)*+ ] )
)
(?: # two possible entry points
\G(?!\A) # 1. contiguous to a previous match
| # OR
[^[]* \[ # 2. all characters until an opening bracket
)
# all possible characters until "," or the closing bracket:
[^]["]* # all that is not ] [ or "
(?:
\g<nestedBrackets> [^]["]* # possible nested brackets
| # OR
"(?!,") [^]["]* # a quote not followed by ,"
)*+ # repeat as needed
\K # remove all on the left from match result
(?:
"," # match the target
|
] (*SKIP)(*F) # closing bracket: break the contiguity
)/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?(DEFINE)
(?<nestedBrackets> \\[ [^][]* (?:\\g<nestedBrackets>[^][]*)*+ ] )
)
(?: # two possible entry points
\\G(?!\\A) # 1. contiguous to a previous match
| # OR
[^[]* \\[ # 2. all characters until an opening bracket
)
# all possible characters until "," or the closing bracket:
[^]["]* # all that is not ] [ or "
(?:
\\g<nestedBrackets> [^]["]* # possible nested brackets
| # OR
"(?!,") [^]["]* # a quote not followed by ,"
)*+ # repeat as needed
\\K # remove all on the left from match result
(?:
"," # match the target
|
] (*SKIP)(*F) # closing bracket: break the contiguity
)', 'g')
const str = `[word:"pla pla","pla pla","[other_word:"pla pla","[word:"pla","pla"end word]","pla pla"end other_word]","pla pla","[word:"pla","pla"end word]"end word]","`;
const subst = `|,|`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions