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 accomplish 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.
You 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With