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

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

Andrey Kuznetsov
  • 11,440
  • 9
  • 46
  • 70

2 Answers2

37

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

Because the dot . explicitly does not match newline characters.

This would work:

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

because newline characters count as whitespace (\s).

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

Tomalak
  • 322,446
  • 66
  • 504
  • 612
23

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
  • 130,553
  • 41
  • 252
  • 283