Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace opening and closing brackets

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.

like image 680
qazerty23 Avatar asked Aug 28 '18 16:08

qazerty23


1 Answers

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.

like image 166
Wiktor Stribiżew Avatar answered Nov 11 '22 16:11

Wiktor Stribiżew