views:

692

answers:

3

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.

+4  A: 

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

Greg
Exactly what I was looking for, thanks! :-)
okoman
+2  A: 

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
I always find http://regexpal.com/ helpful when I'm working with regexps.
some
A: 

Thanks! The .*? and .+? works!