String Replace Functions

Per another user’s request…(this was previously posted in the Flash 8 area)…
And I have [updated], tested and confirmed that replaceMultiple will work correctly. ( i discovered a misspelling in the previous version).

i have also included method speed information, for those nuts (like myself) that are concerned about processing speed.

replace is recursive, so it is considered Order 1 (uber fast)
replaceMutiple is a single loop, considered Order n (a little slower–but if you’re working with a fixed set of data, you’re good to go!)


/**
* I took out the original version of this function i posted because I realized the snippets sticky had a better way to do this. (plus, this is easier to read)
* this version, however, assumes you want the actual String prototype to modify its contents -- use as needed
* @param String search
* @param String replace
* @return String
*/
String.prototype.replace = function(search:String, replace:String):String {
 this = this.split(search).join(replace);
 return this;
}

/**
* Replaces characters within a string
* replace(Array, string|char)
* Method Speed: n
* @param Array instances
* @param String|char replacement
* @return string
*/
String.prototype.replaceMultiple = function(instances, replacement) {
 for(i=0;i<instances.length;i++)
  this = this.replace(instances*,replacement);
 return this;
}

don’t forget these depend on some code found in the Kirupa tutorial ‘bestof_search’ which scans XML files


/*
* contains()
* @param String
* @return int
*/
String.prototype.contains = function(searchString){
 return (this.indexOf(searchString) != -1);
}
/**
* contains()
* @param String searchvalue
* @return bool
*/
Array.prototype.contains = function(searchValue){
 var i = this.length;
 while(i--) if (this* == searchValue) return true;
 return false;
}

with the aforementioned code and the code below, you can build a tiny xml search engine…which i am currently developing for an application


/**
* GetKeyWords()
* Method Speed: Order n
* Method Type: loop
* @param String query
* @return String[]
*/
GetKeyWords = function(query) {
 var keys= [];
 // the next two lines could be combined, but it's just too hard to read; so they're split up like good like codelings
 query = query.replaceMultiple(punctuation,' '); // spaces are our delimiter, (this could be customized in the method signature, but I don't think it would be any easier to use
 var captured = query.toLowerCase().split(' '); // and as such, we will use them to break up our query into keywords
 for(i=0;i<captured.length;i++)
  if(!isIgnoredWord(captured*, ignoredWords)) keys.push(captured*);
 return keys;
}
/**
* isIgnoredWord(str, array)
* Method Speed: Order 1
* @param String str
* @param Array wordList
* @return bool
*/
isIgnoredWord = function(str, wordList) {
 if(str.length<3) return true;
 return wordList.contains(str.toLowerCase());
}