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.
StrSource = “Now I can find a word In a long string of words in a sentance.”
WScript.Echo(InStr(1,StrSource,” in “))
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?