loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

Javascript replaceAll function

by naspinski 4/5/2009 12:57:00 PM

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'.

Currently rated 3.5 by 52 people

  • Currently 3.500001/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

javascript

Related posts

Comments

4/17/2009 8:08:31 PM

Shawn
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!

Shawn ca


Comments are closed