"a a a a aa".replace(/ /g, "b") 'ababababaa' Can you explain why adding the g causes replace to have t" /> "a a a a aa".replace(/ /g, "b") 'ababababaa' Can you explain why adding the g causes replace to have t" /> "a a a a aa".replace(/ /g, "b") 'ababababaa' Can you explain why adding the g causes replace to have t"/>

when replace has the same behavior as replacesAll

72 views Asked by At
> "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

There are 2 answers

0
Azat Antonyan On BEST ANSWER

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

0
Suhail PM On

This is because g in regular expression denotes all occurences (of space).