ASP Tutorials - Using the Split function to find a substring

The Split function is very useful for extracting part of a string, although it is often overlooked because its use is not obvious.

Extracting a file name from a string

The following example uses the Split function to slice a string into different parts, separated by a delimiter. The original string is a physical file path and the delimiter used for the Split function is the backslash character. A For..Next loop is used to display all the substrings in the array produced by Split. The last entry in the array is the file name.

TestString = "C:\folder\subfolder\filename.ext"
TempArray = Split(TestString, "\")
For I = LBound(TempArray) to UBound(TempArray)
  Response.Write TempArray(I) & "<br>"
Next

The Split function takes a string as one parameter and another string or character as another to specify the delimiter. It returns an array, where each element is the substring between the delimters. The output from the above code is:

C:
folder
subfolder
filename.ext

Notice that the delimiters do not appear in any of the substrings. The Split function would be difficult to use if it was not possible to find the size of the resulting array. This is done using LBound and UBound to find the upper and lower bounds, which are then used to mark the start and end of the For..Next loop.

Extracting a file extension from a string

The previous example can be modified to extract the file extension by using the dot as the delimiter.

TestString = "C:\folder\subfolder\filename.ext"
TempArray = Split(TestString, ".")
Response.Write TempArray(UBound(TempArray))

In this case it is only the last array element that is of interest.

Notes:

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