-3

Why replace function doesn't replace all occurrences?

1) Ex that doesn't work:

//the funcion call
'999.999.999,00'.replace('.', '')

//This replaces only the first match, given as result as below
'999999.999,00'

2) Ex that works, but using regex:

 //the funcion call
'999.999.999,00'.replace(/\./g, '')

//This replaces all matches, given as result as below
'999999999,00'

Is It right for Ex 1? Is It the correct behavior for replace?

Fals
  • 6,813
  • 4
  • 23
  • 43

2 Answers2

2

In your first case you should pass flag as third param:

'999.999.999,00'.replace('.', '', 'g')

More info you can find on MDN. However this is not supported by all browsers and you should use it on your own risk.

antyrat
  • 27,479
  • 9
  • 75
  • 76
1

Yes. JavaScript replace should only replace the first match. If you want to replace multiple of the same string, you should indeed use regular expressions. You could also use a simple while loop:

var match = '.';
var str = '999.999.999,00';
while(str.indexOf(match) != -1) str = str.replace(match, '');

but usually it's much easier to just use Regex. while loops can be faster though. For simple replace actions that would need to be performed on large pieces of text this may be relevant. For smaller replace actions, using Regex is just fine.

Joeytje50
  • 18,636
  • 15
  • 63
  • 95