If you're trying to replace all occurrences of a substring within a string with another string and are having problems then you've come to the right place. This page looks at different ways of doing this and the pro's and cons of each.
Suppose you have the string "The rain in spain falls mainly on the plain." and want to replace all the lowercase a's with the uppercase A. Ideally there would be a replaceAll method on the String that could be used something like this.
This is a set and forget solution that works using the array functions split and join. It turns the original string into an array using the first parameter as a seperator. It then turns the array back into a string, joining the elements with the second parameter.
This works in pretty much all situations and has only one drawback. Because it works using array methods this is the slowest method demonstrated on this page.
One of the things slowing down the replaceAll function is the array manipulation so what if we use a different method? There is a replace method defined for string objects that we can use as follows.
This is pretty easy to do but can be a gotcha if you forget about it. Using this method is significantly faster than using the split/join method and still pretty brainless.
Both the previous methods are quite simple to use but are slowed down by the fact that calling a function takes time. If you are in need of better performance you can just remember the method and use it inline. This provides a substantial improvement.
While faster than the prototype version of the same method this is still fairly slow. It is fastest you'll get if you want to avoid regular expressions though.
Continuing along a similar lines you can use the code from replaceAll2 inline to avoid the time taken to call the function.
This is the fastest method so far but again you need to keep regular expression syntax in mind.
Avoiding the string creation provides a nice boost to performance and this is the fastest implementation there is.
Below is the time taken to replace all occurences of the lowercase 'a' with an uppercase 'A' 5000 times in the string "The rain in spain falls mainly on the plain." using each of the methods above.
If you are after a brainless solution and performance isn't an issue go with the 1st method. It can't get any easier and for most applications it is fast enough.
If performance matters I'd suggest learning a little about regular expressions and using method 5. This will also give you extra flexibility through the wild card and conditional matching provided by regular expressions.