JavaScript: Multiline Replace

Actually I just wanted to replace everything before a certain line using regular expressions. I though that was really really simple. Yes it actually is with real regular expressions as python has them or other languages. But the subset that JavaScript provides just doesn’t support the multiline modifier.
I want:
"12
34"

replace everything before “4″ with nothing, including new lines! I finally want to have:
"4"

I tried some stuff, see some playin of mine here and the final result, that does the job.

>>> "12\n34".replace(/.*3/, "")
"12
4"
>>> "12\n34".replace(/.*3/gi, "")
"12
4"
>>> "12\n34".replace(/.*3/gim, "")
"12
4"
>>> "12\n34".replace(/[\r\n]*3/gim, “”)
“124″
>>> “12\n34″.replace(/[\s\S]*3/, “”) // This works!!!
“4″

All this is copied from Firebug, using Firefox 3.0.4.
Let me explain shortly \s is for all newline and whitespace characters and \S is for all non-whitespace chars. Perfect. That works.

3 Comments »

  1. chris said,

    May 18, 2009 at 4:34 pm

    Thanks a lot, have spent almost an hour figuring this out!!!

  2. Javascript search in replace string funkcije | .: TRSplet - internetne storitve :. said,

    June 17, 2009 at 11:55 am

    [...] Javascript multiline replace [...]

  3. hamish said,

    October 8, 2009 at 2:25 am

    nice one! that’s really annoying. thanks for the fix :)

RSS feed for comments on this post · TrackBack URL

Leave a Comment