This is not a blog. So sue me!


Crikey, things are looking up!

Wednesday, October 15, 2008

ActionScript 2; replace string any number of times

The cheeseparing number of useful String class methods released by Adobe leaves something for the programmer to do. Here is a replace function that will replace a substring within another string any number of times. It starts at the first occurrence.



// replace findThis string from stringIn with replaceWith, repeat number of times
//repeat must be >=1, anything else it will do 1 repeat anyway
// if the string doesn't occur nothing will happen

public static function replaceString(stringIn:String, findThis:String, replaceWith:String, repeat:Number):String {

var stringOut:String = '';
var tempArr:Array;
tempArr = stringIn.split(findThis); //spilt the string into an array based on the occurrences of the target string
stringOut = tempArr[0]; //get the first split item
for (var i=1;i < tempArr.length;i++){
if (i < repeat+1){
stringOut = stringOut + replaceWith + tempArr[i];// replace the next occurrence and add the next split item
}
else {
stringOut = stringOut + findThis + tempArr[i];// restore the rest of the string as it was
}
}
trace("String in: " + stringIn + " String out: " + stringOut);
return stringOut;
}

No comments:

Contributors

St Lawrence Rowing

Test content from SLRC