VBScript InStr function

Definition and Usage

The InStr function can return the position of the first occurrence of a string within another string.

The InStr function can return the following values:

  • If string1 is "" (zero length) - InStr returns 0
  • If string1 is Null - InStr returns Null
  • If string2 is "" - InStr returns start
  • If string2 is Null - InStr returns Null
  • If string2 is not found - InStr returns 0
  • If string2 is found in string1, InStr returns the position of the first occurrence of the matching string.
  • If start > Len(string1) - InStr returns 0

Tip:See also InStrRev function.

Syntax

InStr([start,]string1,string2[,compare])
Parameters Description
start Optional. Specifies the starting position of each search. The default is the first character. If the compare parameter is specified, this parameter must also be specified.
string1 Required. The string to be searched for.
string2 Required. The string to be searched.
compare

Required. Specifies the type of string comparison to use. The default is 0. The following values can be used:

  • 0 = vbBinaryCompare - Execute binary comparison.
  • 1 = vbTextCompare - Execute text comparison.

Instance

Example 1

dim txt,pos
txt="This is a beautiful day!"
pos=InStr(txt,"his")
document.write(pos)

Output:

2

Example 2

dim txt,pos
txt="This is a beautiful day!"
'A textual comparison starting at position 4'
pos=InStr(4,txt,"is",1)
document.write(pos)

Output:

6

Example 3

dim txt,pos
txt="This is a beautiful day!"
'A binary comparison starting at position 1'
pos=InStr(1,txt,"B",0)
document.write(pos)

Output:

0