VBScript: More String Functions - The Middle Man
(Page 4 of 6 )
The Mid() function is also used to parse data from a string. However, unlike the left() and right() functions, it doesn’t technically take from either side. By default, I suppose, it starts on the left side, however you have the option to decide at which position you want to begin taking data. For instance, you could have it start five characters in if you wanted. Here is an example showing Mid() in its default state:
<html>
<body>
<script type="text/vbscript">
ugly="Yo mama so ugly she made an onion cry"
document.write(Mid(ugly,1))
</script>
</body>
</html>
This starts at position one, and prints the entire string:
Yo mama so ugly she made an onion cry
We can specify for it to start after the eighth position (remember to count spaces) like so:
<html>
<body>
<script type="text/vbscript">
ugly="Yo mama so ugly she made an onion cry"
document.write(Mid(ugly,8))
</script>
</body>
</html>
Which gives us:
so ugly she made an onion cry
But what if we only want a certain number of characters? Say we want the first 10 characters. We would use the following code:
<html>
<body>
<script type="text/vbscript">
ugly="Yo mama so ugly she made an onion cry"
document.write(Mid(ugly,1,10))
</script>
</body>
</html>
The first number, 1, tells us where to start. The number 10 tells us how many characters to grab:
Yo mama so
And of course if we wanted to grab fifteen characters but wanted to begin in position eight we would use this code:
<html>
<body>
<script type="text/vbscript">
ugly="Yo mama so ugly she made an onion cry"
document.write(Mid(ugly,8,15))
</script>
</body>
</html>
Giving us:
so ugly she ma
Be careful not to set your beginning position to a number greater than the amount of characters in the string. Try out this code:
<html>
<body>
<script type="text/vbscript">
ugly="Yo mama so ugly she made an onion cry"
document.write(Mid(ugly,100))
</script>
</body>
</html>
The result? A big fat nothing.
Next: Left, Right, Mid…Using Them in a Stupid Way >>
More Windows Scripting Articles
More By James Payne