Javascript string regex /.*/ gm does not capture the entire line at once

Why does javascript string replace 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 am I doing wrong?

+5
source share
3 answers

Let me refer to them in reverse order:

What am I doing wrong?

You want to use +, not *. *means zero or more matches, which makes no sense here. +means one or more matches. So:

"aaa\nbbb\nccc".replace(/.+/g, ".")
// ".\n.\n."

, ^ $ ( ), m ( , ). ^ $, . (, ).

javascript ?

, - .

, *, . , , ; , . : .

:

|

"aaa\nbbb\nccc".replace(/.*/g, function(m) {
    console.log("m = '" + m + "'");
});

:

m = 'aaa'
m = ''
m = 'bbb'
m = ''
m = 'ccc'
m = ''
+6

:

"aaa\nbbb\nccc".replace(/(.*)/gm, ".$1.")

:

".aaa...
.bbb...
.ccc..."

.* aaa .aaa., ...

.* .

T.J. Crowder: .+

"aaa\nbbb\nccc".replace(/.+/g, ".")
+3

, . .*:

/.*/.test("");
// true

/.*/.exec("");
// [""]

, , :

"aaa\nbbb\nccc".match(/.*/g);
// ["aaa", "", "bbb", "", "ccc", ""]
// m flag dropped because ^ and $ are not used

, . \n, :

  • .* aaa
  • - g, aaa
    • .* "" - aaa \n
    • .* \n
    • .* bbb
    • .* "" - bbb \n

. .+, .

+1
source

All Articles