开发者

javascript multiline regexp replace

开发者 https://www.devze.com 2022-12-25 09:24 出处:网络
\"foo\\r\\nbar\".replace(/(foo).+/m, \"bar\") Hello. I can not understand开发者_如何学编程 why this code does not replace foo on bar
"foo\r\nbar".replace(/(foo).+/m, "bar")

Hello. I can not understand开发者_如何学编程 why this code does not replace foo on bar


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消