danspants
danspants

Reputation: 3417

Substring replace in ActionScript 2

I primarily work with AS3 when dealing with flash, but I have a need to use AS2 for a particular project, AS2 is not my friend.

I need to replace a series of substrings within some data on a regular basis. Normally I would create a cleaning function that utilised string.replace() and run my data through it.

However the string.replace() function is missing from AS2 and I haven't found an equivalent. What would be the simplest method for achieving similar functionality?

example:

dirtydata = "I have ABCtoast withABCABC jamABC"

my result would be:

cleandata = "I have toast with jam" 

Upvotes: 0

Views: 8371

Answers (1)

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46395

Do this,

String.prototype.replace = function(searchStr, replaceStr):String { 
    var arr:Array = this.split(searchStr);
    return arr.join(replaceStr);
};  

// initial string with a placeholder
var str:String = 'I have ABCtoast withABCABC jamABC';
// replace ABC with '' and trace it
var replacedStr:String = str.replace('ABC','');
trace(replacedStr)

Else, you could also go for a function performing split and join on the same line.

function stringReplace(block:String, find:String, replace:String):String
{
return str.split(searchStr).join(replaceStr);
}

Upvotes: 2

Related Questions