-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?

5
  • 6
    That is the intended behavior. Commented Jan 30, 2014 at 19:32
  • That's just how it works, check out the docs. Commented Jan 30, 2014 at 19:32
  • 1
    A little reading up on replace could have answered your question Commented Jan 30, 2014 at 19:33
  • @Huangism I bring to stackoverflow only things that I can't fully understand, even after doc reading! Thank you for all the help! Commented Jan 30, 2014 at 19:38
  • 1
    I've included a link to a performance tester in my answer, and the while loops I mentioned are faster than regular expressions. Commented Jan 30, 2014 at 19:45

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Not all browsers support that third parameter. It doesn't work in Chrome. Better to use regex.
@RocketHazmat You are right. Updated my answer.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.