2

I have a simple script which takes two strings and compare them. The first one has a space at the end and the second does not have that.

Function compare(str1,str2)
 dim a 
 If strComp(trim(str1),trim(str2))=0 Then 
     msgbox "OK"
     a=1  
 Else
     msgbox "KO" 
     a=0
 End If    

 compare=a

End Function

I use this function in this way:

s1=     SUCCESSFULLY CONNECTED
s2=     SUCCESSFULLY CONNECTED
result=compare(s1,s2)

The difference between s1 and s2 is that s1 ends with a single space while s2 does not have any space at the end. This why I use the Trim function to ignore that space. Despite that, for s1 and s2, I always get the message "KO" in dialog box. I have even changed the condition by

If trim(str1)=trim(str2) Then

But popup is still returned "KO". This is a wonderful situation!

Please, I'm tired of that and hope that you help understand this situation. Thank you in advance

new
  • 1,109
  • 5
  • 21
  • 30

2 Answers2

5

VBScript's Trim removes spaces/blanks, not other kinds of whitespace. You'll need a RegExp to clean strings with leading/trailing vbTab, vbCrLf, ... which you often get, when you process the output of .Run or. Exec.

Demo snippet:

>> s1 = "abc" & vbCrLf & " "
>> s2 = "abc"
>> WScript.Echo Len(s1), Len(s2)
>> set r = New RegExp
>> r.Global = True
>> r.Pattern = "^\s+|\s+$"
>> s1 = r.Replace(s1, "")
>> s2 = r.Replace(s2, "")
>> WScript.Echo Len(s1), Len(s2)
>> WScript.Echo CStr(s1 = s2)
>>
6 3
3 3
True
Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96
  • Please, How do I get a Regex which only deletes space at the end of string while maintaining a robust comparison? Thanks – new Jul 16 '13 at 11:48
  • Great! Thank you very much to you, you get me break the impasse. Thanks – new Jul 16 '13 at 12:29
1

You might like to try this:

Dim str1, str2
str1 = "help"
str2 = "Me"
WScript.Echo str1 & str2
str1 = str1 & vbTab
WScript.Echo str1 & str2
WScript.Echo len(str1) & " " & len(str2)
If Right(str1,1) = vbTab Then
    WScript.Echo left(str1,Len(str1) - 1) & str2
Else
    WScript.echo "Oops"
End If

Note that the trailing vbTab added to str1 is now removed simply by removing the last character.

This is useful if you want to preserve the inner VbTabs if you were going to use them to split the string into an array, for example.

Joshua Dwire
  • 5,415
  • 5
  • 29
  • 50