Why does javascript replace string function do this?
"aaa\nbbb\nccc".replace(/.*/gm, ".")
// result = "..\n..\n.." but expected was: ".\n.\n."
"aaa\nbbb\nccc".replace(/^.*/gm, ".")
// result = ".\n.\n." -> OK!!!
"aaa\nbbb\nccc".replace(/.*$/gm, ".")
// result = "..\n..\n.." but expected was: ".\n.\n."
What I am doing wrong?
Let me address those in reverse order:
You want to use
+, not*.*means zero or more matches, which makes no sense here.+means one or more matches. So:Also note that if you’re not using
^or$(your first example), you don’t need themmodifier (but that wasn’t the problem with what you were doing). And you don’t need^or$because.doesn’t match newlines (something I didn’t know prior to answering this question).I have no Earthly idea and hope someone else does.Again, by using
*you’re saying zero or more matches. So it matches all of the relevant characters, replacing them with the first dot; then it matches zero characters, replacing them with one dot. Result: Two dots.Proof:
Live copy | Live source
Outputs: