VBScript: Functioning with Strings - Checking If It’s In With the InStr() Function
(Page 2 of 4 )
The InStr() function can be used for a number of purposes. For starters, you can use it to see if a particular string contains another character or string, as in the following sample:
<html>
<body>
<script type="text/vbscript">
dim toon
dim where
toon="George, George, George of the jungle."
where=InStr(1,toon,"j",0)
document.write(where) & "<br />"
where=InStr(toon,"of")
document.write(where)
</script>
</body>
</html>
In the above sample we assign a value to the variable toon, then use the InStr() function to check whether the character “j” is in the string. It then prints the position at which the first occurrence of “j” appears. Next we use InStr() to check whether the string “of” is in the toon variable. Once more, we print the position of the first occurrence of, well…”of”. Here is the result:
31
24
This means if you count 31 characters (including spaces) into the variable, you will find “f”. Likewise, if you count 24 characters in, you will find the first occurrence of the word “of”.
But what if a character or string is not found? Observe this code:
<html>
<body>
<script type="text/vbscript">
dim toon
dim where
toon="George, George, George of the jungle."
where=InStr(1,toon,"o",0)
document.write(where) & "<br />"
where=InStr(toon,"forest")
document.write(where)
</script>
</body>
</html>
Here we search for the character “o” and the string “forest”. The character “o” is found a number of times, but remember that InStr() only returns the position of the first occurrence. The string “forest” is not found, and so a “0” is returned.
Here is the result:
3
0
In all of the above examples, we begin our search with the first character in the toon variable. There is an option with the InStr() function that lets you decide from which position to begin searching. For instance, if we wanted to begin our search after the first word “George,” we would start the search position at 6, like so:
<html>
<body>
<script type="text/vbscript">
dim toon
dim where
toon="George, George, George of the jungle."
where=InStr(6,toon,"o",0)
document.write(where) & "<br />"
where=InStr(toon,"forest")
document.write(where)
</script>
</body>
</html>
As you can see, the program now returns the first occurrence of “o” at position 11, instead of 3, as in our previous example.
Here is the result:
11
0
You may also have noted in the above code (where=InStr(6,toon,"o",0) that after the criteria “o”, there was a 0. This is an optional piece of code that lets you specify whether to do a binary (0) or textual (1) search.
Next: Using InStr() with Variables >>
More Windows Scripting Articles
More By James Payne