Question: Why does
'mop' rather than
string.replace('str1','str2') method will only replace the first occurrence of
str1 in the
string. Thatís how the
replace() method treats its string arguments.
Note that both arguments
'str2' in the above example are strings.
In order to replace all occurrences of
str1, you'd need to supply a regular expression,
rather than a string
'str1', as the first argument of
and also specify the regular expression flag
g (global), like this:
s1 = 'pop'.replace('p','m') // result: 'mop' (only the first 'p' replaced) s2 = 'pop'.replace(/p/g,'m') // result: 'mom' (all occurrences of 'p' replaced)