About Me

Friday, 20 April 2012

ASP Strings

ASP Strings

This lesson will tell you how to use strings in ASP. VBScript is the default scripting language for ASP, so if you know VBScript strings inside and out you will already know everything you're about to read!

ASP Creating a String

To create an ASP String you first declare a variable that you wish to store the string into. Next, set that variable equal to some characters that are encapsulated within quotations, this collection of characters is called a String.
Below we set our variable myString equal to string of characters "Hello There!".

ASP Code:

<%
Dim myString
myString = "Hello There!"
%>

ASP Concatenating Strings

Throughout your ASP programming career you will undoubtedly want to combine multiple strings into one. For example: you have someone's first and last name stored in separate variables and want to print them out as one string. In ASP you concatenate strings with the use of the ampersand (&) placed between the strings which you want to connect.
Below we have set up this situation and added a twist. After we combine the names into one string we will be adding this string variable to the temporary string "Hello my name is ".

ASP Code:

<%
Dim fname, lname, name
fname = "Teddy"
lname = " Lee"
name = fname & lname
Response.Write("Hello my name is " & name)
%>

Display:

Hello my name is Teddy Lee

ASP Concatenating Numbers

Besides just concatenating strings onto other strings you can just as easily add on numbers to strings, or numbers to numbers to make strings. Below are a couple of integer to string examples.

ASP Code:

<%
Dim fname, myAge, myHeightM, allOfIt
myAge = 7
myAge = myAge & 5
myHeightM = 2
fname = "Teddy"
allOfIt = fname & " is " & myAge & " years old and "
allOfIt = allOfIt & myHeightM & " meters tall" 
Response.Write(allOfIt)
%>

Display:

Teddy is 75 years old and 2 meters tall

ASP Convert String to Date

To perform an ASP String to Date conversion you need to utilize the CDate function (stands for Convert Date). This will take a String that contains a date and change it into a properly formatted ASP Date.
In our example below we create a string, check to see if it can be converted into a date with isDate and then perform the conversion.

ASP Code:

<%
Dim myStringDate, myTrueDate
myStringDate = "August 18, 1920"
If IsDate(myStringDate) Then
 myTrueDate = CDate(myStringDate)
 Response.Write(myTrueDate)
Else
 Response.Write("Bad date formatting!")
End If
%>

Display:

8/18/1920
Our string myStringDate was a properly formatted date and was successfully converted and written to the browser.

0 comments:

Post a Comment