ASP Tutorials - Finding the length of a string

The Len function in VBScript returns the number of characters stored in a string.

The following example displays the length of a string.

Response.Write Len("Some Text.")

The result is 10, because it countds the 8 letters, the space in the middle and the dot at the end.

Leading and trailing spaces are also counted, so the following code gives a value of 16, because there are three leading spaces and three trailing spaces.

Response.Write Len(" Some Text. ")

Removing spaces from the start or end of a string

It is often necessary to remove spaces from the start and end of a string (called leading and trailing spaces). This might be done to clean and standardise user entered data. The LTrim and RTrim functions are used (Left Trim and Right Trim) to remove spaces from either end of the string. The Trim function removes the spaces from both ends.

The string from the previous example will be used and then left trimmed and right trimmed

CurrentString = "   Some Text.   "
Response.Write "Start: " & CurrentString & " - Length: " & Len(CurrentString) & "<br>"
CurrentString = LTrim(CurrentString)
Response.Write "After LTrim: " & CurrentString & " - Length: " & Len(CurrentString) & "<br>"
CurrentString = RTrim(CurrentString)
Response.Write "After RTrim: " & CurrentString & " - Length: " & Len(CurrentString) & "<br>"

The variable CurrentString stores the string as it passes through the script and the length is displayed after each step. Trim could have been used to remove the spaces instead of using the two commands, LTrim and RTrim.

Notes:

The sample code in these tutorials is written for VBScript in classic ASP unless otherwise stated. The code samples can be freely copied.