29 June 2010

AS2: Simple, Powerful String Find & Replace all instances function for Flash Actionscript. Similar to PHP's str_replace replacement.

Exactly what it says on the tin!

AS3 version here



Please see right hand panel before copying>

//needle and/or replacement can be either a string or an array of strings:
_global.str_replace=function(needle, replacement, haystack:String) {
 var r=haystack;
 if(typeof(needle)=="string"){
  needle=Array(needle)
 }
 if(typeof(replacement)=="string"){
  replacement=Array(replacement)
  
 }
 while(replacement.length<needle.length){
  replacement.push(replacement[replacement.length-1])
 }
 for(var i in needle){
  r=r.split(needle[i]).join(replacement[i])
 }
 return(r)
}
/*SAMPLE USAGE:
trace( strreplace("A","X","ABCDEFG") )  //outputs: XBCDEF
trace( strreplace(Array("A","B","C"),Array("X","Y","Z"),"ABCDEFG") )  //outputs: XYZDEF
*/

No comments:

Post a Comment

Cron Design Studio: Dublin based web design & software development