Find and Replace
A "Find and Replace" method is always handy when trying to avoid repetition in code (especially when replacing variables in XML Strings) and so here's a quick script everyone should know:
public static function replaceWord (searchString:String, find:String, replace:String) : String { var wordLength = searchString.length; var result:String = ''; for (var i = 0; i < wordLength; i++) { if (searchString.substr (i, find.length) == find) { result = searchString.substr (0, i) + replace + searchString.substr (i + find.length, wordLength); } } if (result == '') result = searchString; // didn't replace anything return result; }
2 Comments
→
I love those kind of utility functions that make your life easier… I use a different method in my StringUtils class to achieve the find and replace functionality. Basically does the same thing, just with less lines of code :P
public static function replace(searchString:String, find:String, replace:String):String {
return searchString.split(find).join(replace);
}
It uses the split() method of String classes, that turns the original string into an array with the search string being the delimiter, thus removing it. Then you join the array back together with the new string as seperator (which inserts it). Should the searchterm not exist, then the array will only have 1 node, so nothing will have to be joined and the old string gets returned… Same result, different method… I love to see how everyone approaches those problems differently. By comparing the methods you can learn so much…
Just found (and bookmarked) your blog btw since you linked it on Kontain… I always have big plans for mine but never find the time to really get it going…
Ha! How right you are. It’s funny how knowing the basics can make life so much easier. I’m definitely swapping out my method with that haha.