skip to Main Content
> "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?

2

Answers


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

    Login or Signup to reply.
  2. This is because g in regular expression denotes all occurences (of space).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search