Go to: Articles List
There are 7 functions available in ASP to help you parse strings. Below I explain
each one individually.
InStr(StringBeingSearched, StringSearchingFor)
-returns the position at which the string being searched for was found.
-returns 0 if StringBeingSearched is zero-length.
-returns 0 if StringSearchingFor is not found.
-returns null if StringBeingSearched or StringSearchingFor is null.
Example:
str1 = "Hello."
str2 = "ll"
If InStr(str1,str2) > 0 Then
Response.Write("str1 contains str2")
Else
Response.Write("str2 is not in str1")
End If
Result:
Prints out "str1 contains str2"
InStrRev()
-sames as InStr(), except starts from right side of string
Left(StringToPullFrom,NumOfCharsToPull)
-returns the requested number of characters starting from the left side
Example:
str1 = "abcdefg"
Response.Write("The first three characters of str1 are " & Left(str1,3))
Result:
Prints "The first three characters of str1 are abc"
Right()
-returns the requested number of characters starting from the right side
Example:
str1 = "abcdefg"
Response.Write("The last three characters of str1 are " & Right(str1,3))
Result:
Prints "The last three characters of str1 are efg"
Mid(StringToPullFrom, CharToStartWith[, LengthOfCharsToPull])
-bracketed parameters are optional
-returns the requested number of characters from a string
-if LengthOfCharsToPull is left out, Mid will return all of the characters
starting from CharToStartWith
Example:
str1 = "abcdefghi"
Response.Write("Mid(str1, 3, 3)=" & Mid(str1, 3, 3))
Result:
Prints "cde"
Replace(StringToReplaceIn, FindThis, ReplaceWithThis[, StartHere,ThisManyTimes])
-bracketed parameters are optional
-returns a string with FindThis replaced with ReplaceWithThis started at
StartHere and done ThisManyTimes
-if StartHere is left out Replace will begin at the first character
-if ThisManyTimes is left out Replace will be done throughout the supplied
string
Example:
str1 = "This*is*my*story!"
Response.Write("Replace * with a space = " & Replace(str1, "*", " "))
Result:
Prints "Replace * with a space = This is my story!"
Len(StringToCheck)
-returns that length of the supplied string
-can be used in conjunction with the other string parsing functions
Example:
str1 = "abcdefghi"
Response.Write("Left(str1, Len(str1)-2)=" & Left(str1, Len(str1)-2))
Result:
Prints "abcdefg"
Combine these functions all together to parse strings.
Example:
If str1 contains a '1' as the second char then change the first three to
'714'
str1 = "212-555-1212"
Response.Write("str1=" & str1 & "<br>")
'Check for the '1'
If Mid(str1, 2, 1) = "1" Then
'Remove the first three chars
newstr = Right(str1, Len(str1)-3)
Response.Write("BEFORE newstr=" & newstr & "<br>")
'Add '714' to the beginning
newstr = "714" & newstr
Response.Write("AFTER newstr=" & newstr & "<br>")
End If
Result:
Prints out:
str1=212-555-1212
BEFORE newstr=-555-1212
AFTER newstr=714-555-1212
|
|
|
|