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

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

2 Answers 2

45

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I didn't know. In ruby it does by default.
[\s\S] is a much better workaround than (?:.|\s); see Erik Corry's answer to this question for the reason: stackoverflow.com/questions/2407870/…
26

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 ..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.