InStr - VBScript


InStr

Overview:

The InStr command finds the first occurrence of a specified substring within a string. It’s commonly used to search for specific text or patterns within larger strings.

Syntax:

InStr(<Start>, <String>, <Substring>)

Parameters:

  • Start: (Optional) The starting position in the string to begin the search. Defaults to 1 (beginning of the string).
  • String: The string within which to search for the substring.
  • Substring: The substring to find within the string.

Options/Flags:

  • vbBinaryCompare: (Optional flag) Performs a binary comparison, which is case-sensitive. Defaults to vbTextCompare.
  • 1 (vbTextCompare): (Default) Performs a text comparison, which is case-insensitive.

Examples:

' Find the first occurrence of "VB" in "Visual Basic":
Dim pos = InStr("Visual Basic", "VB")

' Find the first occurrence of "NET" in "VB.NET", starting from position 4:
Dim pos = InStr(4, "VB.NET", "NET")

Common Issues:

  • If the substring is not found, it returns 0.
  • Using the vbBinaryCompare flag in a different locale may yield unexpected results due to differences in character encoding.

Integration:

InStr can be used with other VB Script commands to perform advanced text manipulation. For example, it can be combined with Mid to extract the found substring:

Dim pos = InStr("This is a test", "is")
Dim substring = Mid("This is a test", pos, 2)
  • InstrRev: Finds the last occurrence of a substring.
  • String.IndexOf: .NET equivalent of InStr.