javascriptnode.jsregexreplacereplaceall

when replace has the same behavior as replacesAll


> "a a a a aa".replace(/ /, "b")
'aba a a aa'
> "a a a a aa".replace(/ /g, "b")
'ababababaa'

Can you explain why adding the g causes replace to have the behavior of replaceAll?


Solution

  • The 'g' flag stands for "global" and is used to specify that a regular expression should perform a global search. This means that the regex engine will search for all occurrences of the pattern in the input string, rather than stopping after the first match. By default, without the 'g' flag, the regex engine will return only the first match found.

    Thats why in your first example it only replaced first occurence and in second all of occurences