Replace - VBScript


Overview

The Replace command in VB Script performs a search and replace operation on a given string. It replaces all occurrences of a specified substring (oldValue) with a replacement substring (newValue). This command is commonly used for altering text, manipulating data, or modifying XML elements.

Syntax

Replace(string, oldValue, newValue, [count], [compare])

| Parameter | Description | Default Value |
|—|—|—|
| string | The string to replace text within | Required |
| oldValue | The substring to locate and replace | Required |
| newValue | The replacement substring | Required |
| count | Specifies the maximum number of replacements; “-1” for all occurrences | -1 |
| compare | Case-sensitive comparison (false) or case-insensitive comparison (true) | false |

Options/Flags

  • Compare: Controls case-sensitivity lors of the search operation.

Examples

' Replace all instances of "hello" with "hi"
Dim str = Replace("hello world", "hello", "hi")
' Replace only the first occurrence of "there" with "here"
Dim str = Replace("there is no place like home", "there", "here", 1)
' Replace "USA" with "US" in an XML string
Dim str = "<address>123 Main St, Anytown, USA</address>"
str = Replace(str, "<br><br>USA", "<br><br>US")

Common Issues

  • Ensure that oldValue matches the desired substring to avoid unexpected replacements.
  • For case-insensitive comparisons, set the compare flag to true.
  • If count is set to 0, no replacements will be made.

Integration

The Replace command can be combined with other VB Script commands or tools like:

  • InStr to find the position of a substring before replacing.
  • String concatenation to modify or insert text.
  • XMLDOM to manipulate XML elements, such as replacing node values.
  • InStr
  • LCase
  • UCase