31

I wonder if there is a way to use ungreedy matching in JavaScript? I tried the U modifer, but it doesn't seem to work.

I want to write a small BBCode parser in JavaScript, but without ungreedy matching it isn't possible (at least as far as I see it) to do something like this:

'[b]one[/b] two [b]three[/b]'.replace( /\[b\](.*)\[\/b\]/, '<b>$1</b>' );

But such a replacement would be nice since there is no need to check for HTML validity then. Unclosed markups will stay simple text.

okoman
  • 5,529
  • 11
  • 41
  • 45

2 Answers2

66

You can use ? after * or + to make it ungreedy, e.g. (.*?)

Greg
  • 316,276
  • 54
  • 369
  • 333
  • 1
    Incredible, but it just works! Thanks. in other enviroments, the flag /u (ungreedy) can be used. But for javascript methods is not available (with exception of nodejs methods, i think) – julianm Oct 19 '17 at 15:00
  • Please could you try to explain the logic behind this trick ? – St3an Apr 30 '21 at 08:49
  • 1
    @St3an there isn't a logic behind this trick to explain. `*` and `*?` are two different quantifiers. `*` is the greedy quantifier (match zero to unlimited times as many times as possible) `*?` is the lazy quantifier (match zero to unlimited times as few times as possible). Fun fact: Using the flag `U` (Ungreedy) seems to revers the meaning. However the flag isn't supported by js and the lowercase `u` is the unicode-flag. – Lukas Thiersch Apr 13 '23 at 13:09
4

I'm late, but I'll post the regex anyway.

'[b]one[/b] two [b]three[/b]'.replace( /\[b\](.+?)\[\/b\]/g, '<b>$1</b>' );
cLFlaVA
  • 1,468
  • 3
  • 13
  • 17