ASP Tutorials - Using the InStr function to find a substring

The InStr function is used to find the first occurrence of a substring or character in a string. This value can then be used with the Left, Right or Mid functions to remove part of the string.

Example of using InStr

The following example finds the position within a string of the letter "s".

SampleString = "A sample string to use with the InStr function."
Response.Write InStr(SampleString, "s")

This displays the number 3, because the first letter s is the third character in the string.

Using InStr to count the occurrences of a character

InStr has an optional parameter for the start of the search within the string. This allows InStr to be used in a loop to count the occurrences of a character or substring.

SampleString = "A sample string to use with the InStr function."
Finished = false
Count = 0
Start = 1
While not Finished
  Position = InStr(Start, SampleString, "s")
  If Position = 0 Then
    Finished = true
  Else
    Start = Position + 1
    Count = Count + 1
  End If
WEnd
Response.Write Count

This displays the number 3 because there are three lower case instances of the letter s in the string. The start parameter for InStr must be greater than zero, or it will generate an error. When it is used inside a loop, as in this example, it must always be set to one more than the position found, otherwise the loop will be infinite. This code can be modified to find the position of each specified character, or the position of the last occurrence of the character.

If you are trying to extract a sub string from the end of the string, using a delimiter character, such as finding a file extension, it is easier to use the Split function as in this example.

Removing a substring using Left, Right or Mid

Left returns a specified number of characters from the left of a string.

Right returns a specified number of characters from the left of a string.

Right returns a substring given the start and length of the substring.

SampleString = "A sample string to use with the InStr function."
Response.Write Left(SampleString, 10) & "<br>"
Response.Write Right(SampleString, 10) & "<br>"
Response.Write Mid(SampleString, 5, 10)

These three lines display the first 10 characters of the string, then the last 10 characters, and then the 10 characters which start with the 5th character.

Notes:

The sample code in these tutorials is written for VBScript in classic ASP unless otherwise stated. The code samples can be freely copied.