VBScript: Functioning with Strings - Using InStr() with Variables
(Page 3 of 4 )
You can also test to see whether or not the value in a variable is in a string and have it print the position where the value begins, like so:
<html>
<body>
<script type="text/vbscript">
dim ape
dim toon
dim where
toon="George, George, George of the jungle."
ape="the"
where=InStr(1,toon,"o",0)
document.write(where) & "<br />"
where=InStr(toon,ape)
document.write(where)
</script>
</body>
</html>
This code will result in:
3
27
Working with the InStrRev() Function
As you can imagine, the InStrRev() function works like the InStr() function, only in reverse. It begins searching from the end of the string and works its way to the front. Here are some examples showing how it works:
<html>
<body>
<script type="text/vbscript">
dim gump,where
gump="Ugly is as ugly does"
where=InStrRev(gump,"ugly")
document.write(where)
</script>
</body>
</html>
The result of this code is:
12
If we had used the InStr() function, it would have found the first instance of the word “ugly” at position 1, or at the beginning of the string. However, with the InStrRev() function, we begin searching at the end of the string and thus, find the first occurrence of “ugly” at position 12 instead.
And just as you can specify the location for the search to begin with InStr(), so too can you using InStrRev:
<html>
<body>
<script type="text/vbscript">
dim gump,where
gump="Ugly is as ugly does"
where=InStrRev(gump,"ugly",19)
document.write(where)
</script>
</body>
</html>
Here, we begin the search at the nineteenth position and we again find the first occurrence of “ugly” at position 12.
Next: Uppercase and Lowercase >>
More Windows Scripting Articles
More By James Payne