Creating a Function That Will Search and Replace in Strings
<html> <head> <title>Creating a Function That Will Search and Replace in Strings</title> </head> <body> <script language="JavaScript1.1" type="text/javascript"> <!-- function stringReplace(originalString, findText, replaceText) { var pos = 0; var len = findText.length; pos = originalString.indexOf(findText); while (pos != -1) { preString = originalString.substring(0, pos); postString = originalString.substring(pos + len,originalString.length); originalString = preString + replaceText + postString; pos = originalString.indexOf(findText); } return originalString; }
var origString = new String("This is a test"); var findString = new String("i"); var replaceString = new String("I"); var resultString = stringReplace(origString, findString, replaceString)