![]() |
Table of Contents |
![]() |
Strings in VBScriptAs you learned in Chapter 5, VBScript can store any type of data in a variable. String data is anything VBScript cannot interpret as another data type, such as a number or a date. Strings are simply any combination of letters, numbers, spaces, symbols, punctuation, and so forth. Often times, VBScript might interpret data as different types. For example, 5/7/2003 could be treated as a date or as a string, because it qualifies as both. In those instances, VBScript will coerce the data into one type or the other, depending on what you're trying to do with the data. Coercion is an important concept, especially when dealing with strings. For more information, refer to "What Are Variables?" in Chapter 5. In your scripts, you'll always include strings within double quotation marks, which is how you let VBScript know to treat data as a string. For example, all of the following are acceptable ways to assign string data to a variable. Var = "Hello" Var = ""Hello"" Var = "Hello, there" Var = vSomeOtherStringVariable The second example is worth special attention. Notice that two sets of double quotes were used: This method will cause the variable Var to contain a seven-character string that begins and ends with quotes. Use this technique of doubling-up on quote marks whenever you need to assign the quote character itself as a part of the string. VBScript refers to any portion of a string as a substring. Given the string Hello, one possible substring would be ell and another would be ello. The substring ello has its own substrings, including llo and ell. VBScript provides a number of functions for working with substrings. For example, you might write a script that accepts a computer name. The user might type just the name, such as Server1, or he might include a UNC-style name, such as \\Server1. Using VBScript's substring functions, you can get just the substring you want. A large number of VBScript's intrinsic functions are devoted to string manipulation, and I'll cover most of them in this chapter. As a quick reference, here's each one, in alphabetical order, along with a quick description of what each does.
You should realize that none of these functions change the contents of a string variable. For example, Var1 = Trim(Var2) does not change the contents of Var2. Instead, it trims all spaces from the left and right ends of Var2's contents, and assigns the result to Var1. If you want to change the contents of a variable, you can use something like Var1 = Trim(Var1). Internally, VBScript creates a new string to hold the result of the Trim() function, and then assigns that result back to the Var1 variable. This behind-the-scenes assignment is what actually changes the contents of Var1, not the Trim() function. |
![]() |
Table of Contents |
![]() |