PDA

View Full Version : Search and Replace



mpelland
September 28th, 2005, 05:01 PM
hey,
i am looking to create something similar to the str_replace function (from PHP) that will replace all occurrences of the search string the replacement string from within an larger string. Does anyone have something like that created already (save me the time)?

ie
var myStr:String = new String( "i wish i were an oscar meyer weiner" );
var myOutput = str_replace(myStr, "i", "we");

// myOutput would now = "we wish we were an oscar meyer weiner"

stringy
September 28th, 2005, 05:54 PM
hey,
i am looking to create something similar to the str_replace function (from PHP) that will replace all occurrences of the search string the replacement string from within an larger string. Does anyone have something like that created already (save me the time)?

ie
var myStr:String = new String( "i wish i were an oscar meyer weiner" );
var myOutput = str_replace(myStr, "i", "we");

// myOutput would now = "we wish we were an oscar meyer weiner"

this is the function i normally use (not written by me)


String.prototype.searchReplace = function(find, replace) {
return this.split(find).join(replace);
};

but this doesn`t work in your case
i`ve modified it slightly to look for words -not tested much but may help


String.prototype.searchReplace = function(find, replace) {
var myarray = this.split(" ");
for (var i = 0; i<myarray.length; i++) {
if (myarray[i] == find) {
myarray[i] = replace;
}
}
return myarray.join(" ");
};
var myStr = "i wish i were an oscar meyer weiner";
var myOutput = myStr.searchReplace("i", "we");

mpelland
September 28th, 2005, 06:01 PM
excellent.. thanks.. i am at the point today where i don't really want to think anymore .. so that was great.

stringy
September 28th, 2005, 06:05 PM
excellent.. thanks.. i am at the point today where i don't really want to think anymore .. so that was great.
welcome