views:

129

answers:

2
"foo\r\nbar".replace(/(foo).+/m, "bar")

Hello. I can not understand why this code does not replace foo on bar

+3  A: 

Because the dot . explicitly does not match newline characters.

This would work:

"foo\r\nbar".replace(/foo(?:.|\s)+/m, "bar")

because newline characters count as whitespace \s.

Note that the parentheses around foo are superfluous, grouping has no benefits here.

Tomalak
Thanks, I didn't know. In ruby it does by default.
SMiX
No it doesn't. ;) (Test for yourself at http://rubular.com/)
Tomalak
`[\s\S]` is a much better workaround than `(?:.|\s)`; see Erik Corry's answer to this question for the reason: http://stackoverflow.com/questions/2407870/javascript-regex-hangs-using-v8
Alan Moore
+5  A: 

JavaScript does not support a dot-all modifier. A common replacement is:

"foo\r\nbar".replace(/(foo)[\s\S]+/, "bar")

/m makes ^ and $ behave correctly, but has not effect on ..

Kobi
Great.Thank you
SMiX