InStr Function archives - The VBScript Network and Systems Administrator's Cafe

The VBScript Network and Systems Administrator's Cafe:

InStr function

Jan 30 2009   1:30AM GMT

Easy String Searches with the VBScript Instr function



Posted by: Jerry Lees
InStr function, String manipulation, strings, string, VBScript, Scripting

I recently had a situation where I needed to find string inside a string to parse the larger string into usable and separate chunks of data. In writing this script, I realized I’ve not shared this gem of a function with you previously… and it really makes matters easier when you are manipulating strings.

That function is the Instr function. When configured with the proper parameters, by default, it will return the FIRST location in a string where a sub-string occurs. (Hint: this is where a mid() function would come in handy after you have that starting location). If the sub-string is not found, the function returns 0. The syntax is as follows:

Instr(StartPostion, StringToSearch,StringtoFind, Compare)

 

 The script I wrote really is a blog entry of it’s own, and will be, but I wanted to first introduce you to this great function and let you have a chance to play with it and see some code in action. Below is an example script that takes a string and searched for specific sub strings, then returns the location in the string where the sub string occurs.

 

Option explicit
Dim StrSource

StrSource = “Now I can find a word In a long string of words in a sentance.”

WScript.Echo(InStr(1,StrSource,”In”))
WScript.Echo(InStr(1,StrSource,”in”))
WScript.Echo(InStr(1,StrSource,” in “))
WScript.Echo(InStr(1,StrSource,”now”))

Below is the output from the script. Notice, the following:

  • The case of in and In in the sub-string being searched for and the positions it returns?
  • Notice the substring “in ” returns something entirely different?
  • Notice the substring now returns 0?

 

23
12
48
0

 

Enjoy!