The VBScript Network and Systems Administrator's Cafe

Jan 30 2009   1:30AM GMT

Easy String Searches with the VBScript Instr function

Jerry Lees Jerry Lees Profile: Jerry Lees

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!

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: