Javascript replaceAll function

javascript .replace() only replaces on instance of a character/string, this will replace them all (with no looping)

This may be well know, but I did not realize this until it broke a js function where I was converting currency to integers; anything over $999,999 would not work right, apparently because the extra comma when you hit $1,000,000 was not getting replaced.

At first I went through and looped though a string, but that turned out to be ugly, and likely not as efficient as it could be. So I rooted around with some regexs and figured out the following, turns out it is clean and simple:

function replaceAll(txt, replace, with_this) {
  return txt.replace(new RegExp(replace, 'g'),with_this);

So now, replaceAll('1,000,000', ',', '') will return '1000000' and *not* '1000,000'.

Comments (1) -

  • Incorrect... String.prototype.replace does replace all … it works just like regex’s in most major languages (i.e. perl/python/ruby):

    'foo foo foo'.replace(/foo/g, 'bar');
    => ‘bar bar bar’

    Mmmmm.... that's good regex!

Pingbacks and trackbacks (5)+

Add comment