Skip navigation

Handle Strings More Easily

Downloads
43309.zip

\[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 scripting problems is dealing with extraneous nonprinting characters in strings. Nonprinting characters (e.g., space, tab, carriage return, line feed) don't have visible symbols. The most common nonprinting characters have ASCII character codes in the 0 to 33 range. For example, text files often use the substitute character, which has an ASCII code of 26, and programming languages frequently use the null character, which has an ASCII code of 0. (For more information about characters' code representations, see the VBScript character table at http:// msdn.microsoft.com/library/en-us/ script56/html/vsmscANSITable.asp.)

You might not notice this problem when displaying data because an extra space or tab at the end of a line isn't apparent. However, if you use Microsoft Word to edit your scripts, particularly if you use Word's click-and-type formatting, Word might insert tabs and spaces at arbitrary locations. For example, the string "MyServer" might become "MyServer ".

As this example shows, nonprinting characters frequently occur at the beginning or end of a string. Although VBScript has functions that let you remove leading spaces (LTrim), trailing spaces (RTrim), and both leading and trailing spaces (Trim) from strings, these functions don't work with other nonprinting characters.

I wrote the SuperTrim function as an improvement to Trim. The script in Listing 1, illustrates how SuperTrim works. SuperTrim removes various nonprinting characters from the beginning and end of a string. You can use SuperTrim to make your scripts that manipulate strings deal more effectively with unreadable data. SuperTrim also lets you indent strings in files that you'll read for data without worrying about the effect of spaces or tabs because the code removes the troublesome special characters. Insert SuperTrim into your code and use it rather than Trim to remove nonprinting characters.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish