DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Actionscript _String Class

02.13.2007
| 8434 views |
  • submit to reddit
        
dynamic class _String {
	// Replace a string or substrings within a string
	static function Replace (the_String, search_String, replace_String, occurrences, backward) {
		if (search_String == replace_String) return the_String;
		var found = 0;
		if (backward == true) {
			var pos = the_String.lastIndexOf(search_String);
			while (pos>= 0) {
				found++;
				var start_String = the_String.substr(0, pos);
				var end_String = the_String.substr(pos + search_String.length);
				the_String = start_String + replace_String + end_String;
				pos = the_String.lastIndexOf(search_String, start_String.length);
				if (found == occurrences) pos = -1;
			}
		}
		else {
			var pos = the_String.indexOf(search_String);
			while (pos>= 0) {
				found++;
				var start_String = the_String.substr(0, pos);
				var end_String = the_String.substr(pos + search_String.length);
				the_String = start_String + replace_String + end_String;
				pos = the_String.indexOf(search_String, pos + replace_String.length);
				if (found == occurrences) pos = -1;
			}
		}
		
		return the_String;
	}
	
	// Convert delimited (comma by default) String to an Array
	static function toArray(string, separator:String) {
		var list = new Array();
		if (typeof(string) == "string"){
			if (separator == undefined) separator = ",";
			if (string == null) return false;
			var currentStringPosition = 0;
			while (currentStringPosition<string.length) {
				var nextIndex = string.indexOf(separator, currentStringPosition);
				if (nextIndex == -1) break;
				var word = string.slice(currentStringPosition, nextIndex);
				list.push(word);
				currentStringPosition = nextIndex+1;
			}
			if (list.length<1) list.push(string);
			else list.push(string.slice(currentStringPosition, string.length));
		} else {
			list.push(string);
		}
		return list;
	}
}