String replace() vs RegExp replace()

JavaScript FAQ | JavaScript Strings and RegExp FAQ  

Question: Why does 'pop'.replace('p','m') produce 'mop' rather than 'mom'?

Answer: The 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 'str1' and '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 replace(), and also specify the regular expression flag g (global), like this: string.replace(/str1/g,'str2').

To summarize:

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)

Copyright © 1999-2011, JavaScripter.net.