Changing Strings
VBScript includes a wide array of functions designed to change strings. I'll start with LCase() and UCase(), which change a variable to lower- or uppercase letters, respectively. Try running the following scriptlet to see how these functions work.
Dim sInput
sInput = InputBox("Enter a string to try.")
MsgBox "All upper: " & UCase(sInput)
MsgBox "All lower: " & LCase(sInput)
These functions can be very useful when dealing with case-sensitive strings, such as passwords, WMI queries, and so forth. Using these functions, you can ensure that the case of the strings is exactly what you need for whatever you're doing.
Combining these functions with the substring functions lets you perform some very powerful tricks. For example, the following function will accept a full user name, such as "john doe," and convert it to the proper name case, where the first letters of each name are capitalized, no matter how you capitalize the input.
Dim sUserName
'get the user name
sUserName = InputBox("Enter user name")
'does it contain a space?
If InStr(1, sUserName, " ") = 0 Then
'no - error message!
MsgBox "Name must contain a space."
Else
'display the name case version
MsgBox "Proper case is " & NameCase(sUserName)
End If
Function NameCase(sName)
'lowercase everything
sName = LCase(sName)
'locate the space position
Dim iPos
iPos = InStr(1, sName, " ")
'build the output
sName = UCase(Left(sName,1)) & _
Mid(sName, 2, iPos-2) & " " & _
UCase(Mid(sName, iPos + 1, 1)) & _
Right(sName, Len(sName)-iPos-1)
NameCase = sName
End Function
Try walking through the NameCase() function to see if you can figure out how it works. It's just using substring functions to pull out the first character of the first name, then the rest of the first name, then the first character of the last name, and then the rest of the last name. The first character of each name is run through UCase() to ensure it's uppercased properly.
Another very cool string-changing function is Replace(). With it, you can replace any occurrence of one substring with another substring, all without affecting the other contents of the main string. Sound complicated? It's not! Just check out this example.
Dim sMsg
sMsg = "Hello, %1%. Today is %2%."
Dim sName
sName = InputBox("What is your name?")
sMsg = Replace(sMsg, "%1%", sName)
sMsg = Replace(sMsg, "%2%", Date)
MsgBox sMsg
Replace() can be incredibly useful in administrative scripts. For now, concentrate on learning how it works-you'll see plenty of examples of its usefulness through this book.
|