Index ¦ Archives ¦ RSS

ungreedy regex in javascript

Estimated read time: 1 minutes

a few days ago i wanted to use ungreedy regexs in javascript. first, let's see what an ungreedy regex is. look at the following example:

>>> "

foo

bar

".replace(/

f.*<\/p>/, '') ""

this is greedy. you want to get something like:

"

bar

"

right?

that would be ungreedy. in some other languages, there is a flag for this (php has 'U'), but in javascript, you need an other trick:

>>> "

foo

bar

".replace(/

f.*?<\/p>/, '') "

bar

"

and yes, that's what we wanted. also it works for .+?, and so on.

ah and as a side note, it seems '.' does not match newlines, so you'll have to work around it like:

>>> "

foo\nbar

baz

".replace(/

f[\s\S]*?<\/p>/, '') "

baz

"

© Miklos Vajna. Built using Pelican. Theme by Giulio Fidente on github.