I have a string of text, for example
[text1] [text2] [text3]
I want to replace "[" character with "${" and "]" character with "}", but only in that case, when "[" is followed up by "]".
For example
[text1] [[text2] [text3]
should result in
${text1} [${text2} ${text3}
How can I acplish that with regex in Javascript?
I wrote something like this
someString = someString.replace(/\[/g, "${");
someString = someString.replace(/]/g, "}");
But it doesn't work for my problem, it just replaces every bracket.
I have a string of text, for example
[text1] [text2] [text3]
I want to replace "[" character with "${" and "]" character with "}", but only in that case, when "[" is followed up by "]".
For example
[text1] [[text2] [text3]
should result in
${text1} [${text2} ${text3}
How can I acplish that with regex in Javascript?
I wrote something like this
someString = someString.replace(/\[/g, "${");
someString = someString.replace(/]/g, "}");
But it doesn't work for my problem, it just replaces every bracket.
Share Improve this question edited Aug 28, 2018 at 16:17 epascarello 208k20 gold badges205 silver badges244 bronze badges asked Aug 28, 2018 at 16:14 qazerty23qazerty23 4912 gold badges6 silver badges17 bronze badges 01 Answer
Reset to default 14You may use
var s = "[text1] [[text2] [text3]";
console.log(s.replace(/\[([^\][]+)]/g, "$${$1}"));
Details
\[
- a[
char([^\][]+)
- Group 1: a negated character class matching any 1+ chrs other than[
and]
(note that inside a character class in a JS regex, the]
char must always be escaped, even if it is placed at the negated class start)]
- a]
char (outside of a character class,]
is not special and does not have to be escaped).
In the replacement pattern, $$
stands for a literal $
char, {
adds a {
char, $1
inserts the Group 1 value and then a }
is added.