As I mentioned in one of my previous posts, Javascript has its own replace function that, when used many times, you would have to resort using a / slash followed by options case insensitive and/or global and enclosing them to the search keyword, some cases may not be applicable to use that function. I scoured the net and found this neat function by Dave Shuck taken from this link.

The problem that I encountered was when I used Javascript’s replace() function with a search keyword that’s dynamic. If say, I want to use a search keyword like photo1 and photo2 and photo3 and place that in a for loop, doing it like this

Notice the question mark i placed? I also tried to use the eval() function to see if appending the variable i would make it work. It didn’t. In the end, I decided to go look for a replaceAll() function in Javascript. At least I don’t have to make one anymore he he he. Here’s the function.

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