Ever needed to replace all the instances of a string in Javascript (or ActionScript)? This function takes three parameters, the string to find, the string to replace it, the string to search and an optional setting to toggle case sensitivity.

Syntax
.replaceAll(target:string, findToRemove:string, replacement:string, [caseSensitive:int=0 ])

function replaceAll(o,t,r,c){if(c==1){cs="g"}else{cs="gi"}var mp=new RegExp(t,cs);ns=o.replace(mp,r);return ns}

Example function call searching the string “Bob, bob and Andy”, looking to replace all occurrences of ‘Bob’ with ‘Fred’ regardless of case.

replaceAll("Bob, bob and Andy", "Bob", "Fred");

Returns ‘Fred, Fred and Andy’.

Use a value of 1 to make the search case sensitive.

replaceAll("Bob, bob and Andy", "Bob", "Fred", 1);

As this is now case sensitive it returns ‘Fred, bob and Andy’.

See this in action.

Want to know more

This is achieved using Javascript’s replace() function and regular expressions. The expanded code is:

function replaceAll(oldStr, removeStr, replaceStr, caseSenitivity){
	if(caseSenitivity == 1){
		cs = "g";
		}else{
		cs = "gi";	
	}
	var myPattern=new RegExp(removeStr,cs);
	newStr =oldStr.replace(myPattern,replaceStr);
	return newStr;
}

A Regular Expression is created and given a flag of ‘g’ or ‘gi’. The g (global) flag does a global search and then ‘i’ a case insensitive search. The caseSenitivity parameter is optional and if not set then a case insensitive replacement takes place.

ActionScript Version

Javascript and Actionscript are ECMAScripts so we can port the above as ActionScript:

function replaceAll(oldStr, removeStr, replaceStr, caseSenitivity:Number=0){
	var cs:String;
    if(caseSenitivity == 1){
        cs = "g";
        }else{
        cs = "gi";
    }
    var myPattern=new RegExp(removeStr,cs);
    newStr =oldStr.replace(myPattern,replaceStr);
    return newStr;
}
///////////// example one /////////////////////
var newStr:String;
newStr = replaceAll("Bob, bob and Andy", "Bob", "Fred");
trace(newStr);
//returns "Fred, Fred and Andy"
///////////// example two /////////////////////
var newStr2:String;
newStr2 = replaceAll("Bob, bob and Andy", "Bob", "Fred", 1);
trace(newStr2);
//returns "Fred, bob and Andy"

The only difference here is the setting of the default case sensitivity value to 0, which is done directly in the parameters.

Use Case

I put this together so that I could get rid of pesky white spaces in a string and replace them with + to create friendlier URLs.

One Thought to “replaceAll() function for Javascript (and ActionScript)”

Leave a Reply to Asker Cancel reply