Ensure accurate string comparisons in ASP pages
As you probably know, the StrComp() function provides a quick way  to compare two strings. 
It takes the following syntax:
 
StrComp( string1, string2, comparemode)
 
VBScript compares the two strings according to either the comparemode argument, 
or the default setting on the server. This function returns 1 if the first string is greater 
than the second string, 0 if the two are equal, and -1 if the first string is less
than the second. However, if you want to compare strings taken from user input, to ensure 
that the results are accurate, remove any extra spaces from the two strings. For example, you 
could use something like:
 
StrComp( Trim(str1), Trim(str2))
Strings with extra spaces will provide inaccurate results. To illustrate, create the following ASP page, 
and then view it in Internet Explorer.
<html>
<head>
<script language="VBScript">
sub mySort()
Dim str1, str2, ary, sCompare
str1 = document.all.txt1.value
str2 = document.all.txt2.value
Select Case StrComp(trim(str1), trim(str2))
    Case 1: sCompare = "greater than"
    Case 0: sCompare = "equal to"
    Case -1: sCompare = "less than"
End Select
MsgBox str1 & " is " & sCompare & " " & str2
end sub
</script>
<body>
    <form>
        <input type="text" id="txt1" /><br /><br />
        <input type="text" id="txt2" /><br /><br />		
        <input type="button" value="Compare" onclick="mySort" />
    </form>
</body>
</html>
 
First, enter an A; into the first field and a Z; into the second, then click the Compare button.  
When you do, VBScript informs you that A is less than Z, as you would expect.  Now, enter a space 
before the Z and click the button again.  This time the message box inaccurately claims that A 
is greater than Z.
 


Active Server Index

Main Index

Search RD Techbase