How to Get a VBScript Substring in ASP
Developing ASP pages involves manipulating strings of data. A string is a group of characters enclosed within quotation marks (such as "John Doe") that includes letters only or a mixture of letters and numbers. A variety of functions is available in VBScript to extract portions of a string, referred to as a substring, so we can manipulate the data further. The following steps show how to use VBScript substring functions with customer records.
- Open your text editor.
- Enter the language directive on the first line of the editor.
<%@ Language= "VBScript" %>
- Enter the following html tags:
<html> <head> <title>SubString Functions</title> </head> <body> <h1>Using VBScript SubString Functions</h1>
- Type the
<%>on a new line in your editor to indicate the beginning of the VBScript.
- Declare the customer variables to be used in your code. In this example we will add customer name, customer address, and product number.
'Declare variables using VBScript Dim name, address, ProductNumber
- Assign values to the string variables and make sure to enclose each string in quotation marks.
'Assign values to the variables using VBScript name="John Doe" address="123 Main St. Miami, Fl" ProductNumber="XYZ-98675"
- Use the Len function
Len(string)to return the total number of characters in a string. We will request the length of the customer's address.
'Obtain the length of address Response.write("The Length of address is " & Len(address)) & "<br />"
- Use the Left function
Left(string, length)to extract a certain number of characters from the left side of a string. We will request the first five characters of the customer's name.
'Extract the first five characters from name Response.write(Left(name,5)) & "<br />"
- Use the Right function
Right(string, length)to extract a certain number of characters from the right side of a string. In this example, we will request the last two characters to retrieve the customer's state.
'Extract two characters from the right of the string address Response.write(Right(address,2)) & "<br />"
- Use the Mid function
(Mid(string, starting number of character, number of characters to extract)to extract characters from any portion of a string by specifying the starting character and the number of characters to extract. In this example, we will extract a specific portion of the product number associated with the customer's account.
'Extract three characters from ProductNumber starting with the fifth character Response.write(Mid(ProductNumber, 5,3))& "<br />"
- Type the following to indicate the end of the script, body, and HTML:
%> </body> </html>
- Save your file as vbsubstring.asp.
- Browse to the location of the file that you just saved and select it.
- The substrings you requested will appear as below in your browser.