Replacing strings with Java and Javascript

Java and Javascript have different ways to replace strings like the feature “find and replace” that you see in text editors.

Java’s replace method is not ideal for noobs but only for people who know about regex. I am not that quite familiar with regex and if you wish to use that replace method under the String class in Java, you’d have to familiarize yourself with it in order to use it. The String class though, has lots of other useful methods that can be used to simulate how a search and replace function works. Here is a workaround method for people who only want a simple search and replace with the search and target both String. No regex knowledge needed.

The replace function contains two options. ‘i’ means the search would be case insensitive and ‘g’ means global, meaning it will search all instances of the search string within the str variable. If you do not include ‘g’ as its option, then only the first instance of the search string will be replaced.

Java and Javascript should have provided simple replace methods that greatly help newbies to these languages. The replaceString() method in Java is a good workaround for easy to use search and replace purposes in java.

Related Posts Plugin for WordPress, Blogger...

3 comments

  1. Isn’t String#replace(CharSequence, CharSeqence) the method you are looking for? It’s a method new with Java 5. Under the hood regex are replacing so the performance can be degraded. Christian

  2. ahh.. ive never checked the 1.5 API for that since ive been with 1.4 since. Though im using 1.6 now i’ve never bothered looking if there are any new methods in 1.6 since I’ve been using that workaround method I have. quite useful for me? will check that CharSequence thing. Might be more performance-better than my method.

  3. I don’t agree with everything in this write-up, but you do make some very good points. Im very interested in this matter and I myself do alot of research as well. Either way it was a well thoughtout and nice read so I figured I would leave you a comment. Feel free to check out my website sometime and let me know what you think.

Leave a Reply

Your email address will not be published. Required fields are marked *