Replace Method (VBScript)
Updated: March 2009
Replaces text found in a regular expression search.
The actual pattern for the text being replaced is set using the Pattern property of the RegExp object.
The Replace method returns a copy of string1 with the text of RegExp.Pattern replaced with string2. If no match is found, a copy of string1 is returned unchanged.
The following code illustrates use of the Replace method.
Function ReplaceTest(patrn, replStr) Dim regEx, str1 str1 = "The quick brown fox jumps over the lazy dog." ' Create regular expression. Set regEx = New RegExp regEx.Pattern = patrn regEx.IgnoreCase = True ' Make replacement. ReplaceTest = regEx.Replace(str1, replStr) End Function MsgBox(ReplaceTest("fox", "cat")) ' Replace 'fox' with 'cat'.
In addition, the Replace method can replace subexpressions in the pattern. The following call to the function shown in the previous example swaps the first pair of words in the original string:
' Swap first pair of words. MsgBox(ReplaceTest("(\S+)(\s+)(\S+)", "$3$2$1"))