VBScript Replace Function



Replace

The Replace Function replaces a specified part of a string with a specific string a specified number of times.

Syntax

Replace(string,find,replacewith[,start[,count[,compare]]]) 
  • string, a Required Parameter. The Input String from to be searched for replacing.

  • find, a Required Parameter. The Part of the String that will be be replaced.

  • replace with, a Required Parameter. The replacement string, which would be replaced against the find parameter.

  • start, an Optional Parameter. Specifies the start position from where the string has to be searched and replaced. Default value is 1.

  • count, an Optional Parameter. Specifies the number of times the replacement has to be performed.

  • compare, an Optional Parameter. Specifies the comparison method to be used. Default value is 0.

    • 0 = vbBinaryCompare - Performs a binary comparison

    • 1 = vbTextCompare - Performs a Textual comparison

Example

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         var = "This is VBScript Programming"

         'VBScript to be replaced by MS VBScript
         document.write("Line 1: " & Replace(var,"VBScript","MS VBScript") & "<br />")

         'VB to be replaced by vb
         document.write("Line 2: " & Replace(var,"VB","vb") & "<br />")

         ''is' replaced by ##
         document.write("Line 3: " & Replace(var,"is","##") & "<br />")

         ''is' replaced by ## ignores the characters before the first occurence
         document.write("Line 4: " & Replace(var,"is","##",5) & "<br />")

         ''s' is replaced by ## for the next 2 occurences.
         document.write("Line 5: " & Replace(var,"s","##",1,2) & "<br />")

         ''r' is replaced by ## for all occurences textual comparison.
         document.write("Line 6: " & Replace(var,"r","##",1,-1,1) & "<br />")

         ''t' is replaced by ## for all occurences Binary comparison
         document.write("Line 7: " & Replace(var,"t","##",1,-1,0) & "<br />")

      </script>
   </body>
</html>

When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −

Line 1: This is MS VBScript Programming
Line 2: This is vbScript Programming
Line 3: Th## ## VBScript Programming
Line 4: ## VBScript Programming
Line 5: Thi## i## VBScript Programming
Line 6: This is VBSc##ipt P##og##amming
Line 7: This is VBScrip## Programming
vbscript_strings.htm
Advertisements