Creating a Function That Will Search and Replace in Strings : String : Language Basics JAVASCRIPT DHTML TUTORIALS


JAVASCRIPT DHTML TUTORIALS » Language Basics » String »

 

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)
   
    document.write("The original string was: " + origString + "<br>");
    document.write("We searched for: " + findString + "<br>");
    document.write("We replaced it with: " + replaceString + "<br>");
    document.write("The result was:  " + resultString);
  //-->
  </script>
</body>
</html>

           
       



-

Leave a Comment / Note


 
Verification is used to prevent unwanted posts (spam). .

Follow Navioo On Twitter

JAVASCRIPT DHTML TUTORIALS

 Navioo Language Basics
» String