Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.

 

senocular.com ActionScript Library

replaceS.as

Name: replaceS() - search and replace with offset
Author: senocular: www.senocular.com
Date: 1899-12-31T00:46:54.100
Documentation:
String REPLACES: yet another search and replace, though with the
option of an offset.
 
Arguments:
- str: string segment to find in the entire string to replace with...
- rep: the string which replaces str
- off: (optional) the offset from which the replacing will start. 0 is the beginning of the
string.  If negative, the offset would start from the end of the string where -1 is the last
character in the string and replace backwards up until the offset.
 
Returns:
- the new string created from replacing all instances of str within offseted portion with rep

Example: 
myString = "aaaaa"
trace(myString.replace("a","b")); // bbbbb
trace(myString.replace("a","b",2)); // bbaaa
trace(myString.replace("a","b",-2)); // aaabb

1
2
3
4
5
6
7
8
9
10
11
String.prototype.replaceS = function (str, rep, chr) {
	var t = (chr < 0) ? this.substr(chr) : this.substr(0,chr);
	var s = str.length;
	var r = rep.length;
	var p = t.indexOf(str);
	while (p != -1){
		t = t.substr(0,p) + rep + t.substr(p+s);
		p = t.indexOf(str,p+r);
	}
	return (chr) ? (chr < 0) ? this.substr(0,this.length+chr)+t : t+this.substr(chr) : t;
}