-4

I am trying to perform this transformation to a string (using javascript):

Input:

[hello]{world}and[good]{night}

Output:

<span class="top">hello<span class="bottom">world</span></span>and<span class="top">good<span class="bottom">night</span></span>

To do that I am using the following regex:

text.replace(/\[(.*)\]\{(.*)\}/gim, "<span class='top'>$1<span class='bottom'>$2</span></span>")

It works correctly when only setting one occurrence of the pattern in a string [hello]{world}

But if I add a string with more than one, the regex matches the first [] and the last {} instead, and prints this:

<span class='top'>hello]{world}and[good<span class='bottom'>night</span></span>

How can I tell regex to match the first pattern and the second pattern instead of matching it as one bigger pattern?

Note that between the [] and {} I expect there to be no text. So [hello]world and good{night} should not be matched.

lpares12
  • 3,504
  • 4
  • 24
  • 45

1 Answers1

0

You need to put ? after .* to make the quantifier lazy, instead of greedy.

const text = '[hello]{world}and[good]{night}'


const result = text.replace(/\[(.*?)\]\{(.*?)\}/gim, "<span class='top'>$1<span class='bottom'>$2</span></span>")


console.log(result)
Mina
  • 14,386
  • 3
  • 13
  • 26