# findAndReplace string function

**URL:** <https://forum.kirupa.com/t/findandreplace-string-function/76731>\
**Category:** open source\
**Created:** [January 20, 2005, 11:30pm UTC](https://forum.kirupa.com/t/findandreplace-string-function/76731 "2005-01-20T23:30:01Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![iloveitaly](https://avatars.discourse-cdn.com/v4/letter/i/7ea924/32.png) [@iloveitaly](https://forum.kirupa.com/u/iloveitaly)\
**Post date:** [January 20, 2005, 11:30pm UTC](https://forum.kirupa.com/t/findandreplace-string-function/76731/1 "2005-01-20T23:30:01Z")

</div>

I have been in need of a find and replace function in flash for awhile now, so i whipped up one today. It works identical (almost) to PHP’s str\_replace() function.

```php

/**
 *@description: a find and replace function that will search a string and find all occurances of "search" and replace it with "replace"
 *
 *@param: find, a string, or an array of strings specfying what string(s) you want to find
 *@param: replace, a string, or an array of string specifying what to replace the strings found with.
 *if no value is specified, a empty string ("") replace value is assumed. If there are less entries in the replace array than in the find
 *array, empty string values are assumes for the rest of the replace values. This value is optional.
 *@param: limit, a limit to the amount of times to exacute the find & replace operation. This value is optional.
 *@returns: the string after the find and replace operations have been completed
 **/
String.prototype.findAndReplace = function(find, replace, limit) {
	var tempString = this, tempParts, pos, loopLength;
	
	if(typeof(find)!=="string") {//then the find and replace is an array
		if(replace === undefined) replace = [""]; //if no replace was specified
		else if(typeof(replace)==="string") replace = [replace]; //if only one replace was specified
	} else {//then they are a string
		//put both of them in array form
		find = [find];
		replace = [relace];
	}
	
	loopLength = find.length; //determines the loop length
	
	for(var a = 0, c = 0; a<loopLength; a++, c = 0) {
		while((pos = tempString.indexOf(find[a]))!==-1) {
			if(limit!==undefined && c>=limit) break;
			
			//split the array into 3 parts
			tempParts = new Array(tempString.substring(0, pos), tempString.substr(pos, find[a].length), tempString.substr(pos+find[a].length));
			tempParts[1] = (replace[a]===undefined)? ("") : replace[a]; //if there was no replace specified give an empty string
			tempString = tempParts[0]+tempParts[1]+tempParts[2];
			
			c++; //increase the counter
		}
	}
	
	return tempString;
}

```
