Introduction
Search and replace is a very useful thing to have for Rich Internet Applications, Actionscript dosent have a built-in function for this purpose.
Other Solutions to this problem almost always involve using flash's built in indexof and substring functions in loops, leading to some very messy code. Yesterday I stumbled upon much easier solution, using String.split and Array.join.
Code
function searchAndReplace(holder, searchfor, replacement) {
temparray = holder.split(searchfor);
holder = temparray.join(replacement);
return (holder);
}
Example Use
myreplaced = searchAndReplace("The quick sliver fox jumped over the lazy
brown dog", "brown", "orange");
trace(myreplaced);
//traces "The quick sliver fox jumped over the lazy orange dog"
The way it works is very simple. The split function splits a string using a given delimitor (in this case the deliminator is the text that you want to search for) and converts it to an array.
Flash's Array.join function converts the elements in an array to strings, inserts the specified separator between the elements (in this case the separator is the replacement text) concatenates them, and returns the resulting string
So in our function the string is exploded into an array at the search term and then that array is imploded back into a string with the individual elements seperated by the replacements for the search terms.