Handle Strings More Easily
SuperTrim is an improvement to VBScript’s Trim function.
August 15, 2004
[Editor's Note: Share your scripting discoveries, comments, problems, solutions, and experiences with products. Email your contributions (500 words or less) to [email protected]. We edit submissions for style, grammar, and length. If we print your submission, you'll get $100.]
One of the most annoying scriptingproblems is dealing with extraneousnonprinting characters in strings.Nonprinting characters (e.g., space,tab, carriage return, line feed) don'thave visible symbols. The most commonnonprinting characters haveASCII character codes in the 0 to 33range. For example, text files often usethe substitute character, which has anASCII code of 26, and programminglanguages frequently use the nullcharacter, which has an ASCII code of0. (For more information about characters'code representations, see theVBScript character table at http://msdn.microsoft.com/library/en-us/script56/html/vsmscANSITable.asp.)
You might not notice this problemwhen displaying data because an extraspace or tab at the end of a line isn'tapparent. However, if you use MicrosoftWord to edit your scripts, particularlyif you use Word's click-and-typeformatting, Word might insert tabsand spaces at arbitrary locations. Forexample, the string "MyServer" mightbecome "MyServer ".
As this example shows, nonprintingcharacters frequently occur at thebeginning or end of a string. AlthoughVBScript has functions that let youremove leading spaces (LTrim), trailingspaces (RTrim), and both leading andtrailing spaces (Trim) from strings,these functions don't work with othernonprinting characters.
I wrote the SuperTrim function asan improvement to Trim. The script in Listing 1, illustrates howSuperTrim works. SuperTrim removesvarious nonprinting characters fromthe beginning and end of a string. Youcan use SuperTrim to make yourscripts that manipulate strings dealmore effectively with unreadable data.SuperTrim also lets you indent stringsin files that you'll read for data withoutworrying about the effect of spaces or tabsbecause the code removes the troublesomespecial characters. Insert SuperTrim into yourcode and use it rather than Trim to remove nonprinting characters.
About the Author
You May Also Like