Archive for December, 2008

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.

Comments (10)