Difference between isEmpty(value) and Trim(value) = "" - vbscript

I'm new to vb i don't get the difference between these 2 statements:
isEmpty(value)
and
Trim(value) = ""
Can you explain it? Are they equals?
edit:
i have a code like this in my example
if isempty(request.form("alias")) then
...
elseif trim(request.form("alias")) = "" then
...
end if

All VBScript variables are Variants, but there are subtypes. An empty/not initialized variable has the subtype Empty. The value of such a variable 'works' like 0 or "" in expressions:
>> Dim EmptyVar
>> WScript.Echo VarType(EmptyVar), TypeName(EmptyVar), 1 + EmptyVar, "a" & EmptyVar & "c"
>>
0 Empty 1 ac
>> WScript.Echo CStr(EmptyVar = 0), CStr(EmptyVar = "")
>>
True True
A string variable (initialized by a literal or a string expression) has the subtype String.
It may be empty - i.e. contain no characters - but such a beast is not of subtype Empty:
>> Dim NixStr : NixStr = ""
>> WScript.Echo VarType(NixStr), TypeName(NixStr), 1 & NixStr, "a" & NixStr & "c"
>>
8 String 1 ac
>>
The VBScript function IsEmpty() checks whether a variable is empty/not initialized:
>> WScript.Echo CStr(IsEmpty(EmptyVar)), CStr(IsEmpty(NixStr))
>>
True False
That is why you should check the return value of Inputbox() with IsEmpty() - did the user cancel/abort - and against "" - did the user try to feed "" to the program.

Trim returns the string without ony spaces on the left or right. Eg, " hello world " will become "hello w world".
isEmpty returns a boolean. If the string is empty ("") it will return true, otherwise it will return false.

Related

VBScript runtime error '800a01a8' when an empty string comes to [duplicate]

What is the quickest and easiest way (in Classic ASP) to check if a string has some string (that has a length greater than 0) i.e. NOT "Null", "Nothing", "Empty", or '' empty string
To make sure that the Variant you deal with is of sub-type "string", you need the VarType or TypeName function. To rule out zero length strings, you need Len(). To guard against strings of space, you could throw in a Trim().
Code to illustrate/experiment with:
Option Explicit
Function qq(s) : qq = """" & s & """" : End Function
Function toLiteral(x)
Select Case VarType(x)
Case vbEmpty
toLiteral = "<Empty>"
Case vbNull
toLiteral = "<Null>"
Case vbObject
toLiteral = "<" & TypeName(x) & " object>"
Case vbString
toLiteral = qq(x)
Case Else
toLiteral = CStr(x)
End Select
End Function
Function isGoodStr(x)
isGoodStr = False
If vbString = VarType(x) Then
If 0 < Len(x) Then
isGoodStr = True
End If
End If
End Function
Dim x
For Each x In Array("ok", "", " ", 1, 1.1, True, Null, Empty, New RegExp)
WScript.Echo toLiteral(x), CStr(isGoodStr(x))
Next
output:
cscript 26107006.vbs
"ok" True
"" False
" " True
1 False
1.1 False
True False
<Null> False
<Empty> False
<IRegExp2 object> False
Here's a one-liner that dodges all the trouble with Null by concatenating the value with an empty string. It works for Null, Empty, "", and, of course, strings with actual length! The only one it doesn't (nor shouldn't) work for is Nothing, because that's for object variables, of which a string is not.
isNullOrEmpty = (Len("" & myString) = 0)
You could try having something like this:
Function nz(valToCheck, valIfNull)
If IsNull(valToCheck) then
nz = valIfNull
Else
nz = valToCheck
End if
End function
and then you would use it like this:
if nz(var,"") <> "" then
'--string has something in it
else
'--string is null or empty
end is
You can use the VarType() function to check if it is a string, then you can check if the string is not empty. This statement will only pass through a string that isn't empty.
If VarType(MyString) = 8 Then
If MyString <> "" Then
'String is Not Null And Not Empty, code goes here
End If
End If
This worked for me:
if mystring = "" then wscript.echo "Empty string"
else wscript.echo "String is not empty"
<%
Dim x,y
x = "abcdefg"
'counting length of string
y = Len(x)
Response.Write (y)
'checking string is empty or not
If Len(x) = 0 then
Response.Write ("<p>String is empty</p>")
Else
Response.Write ("<p>String is not empty</p>")
End If
%>
Hope this is helpful.

Check if string is all capitals using classic asp

I need a function to check if a string is all (or mostly) capitals using classic asp. (I need to prevent users from inputting titles using all capitals.)
For example, if a string of 30 letters contains 20 or more that are capitalized, I'd need to flag it as "All capitals". So "The Count of Monte Cristo" would be fine, but "The COUNT of MONTE CRISTO" would not.
I was thinking about starting with a count of letters that match [^A-Z], but how do I do that?
This needs to be in Classic ASP and not VB.
Comparing against UCase(input) makes it an all or nothing check; I'd prefer to look at the UCase ratio:
Option Explicit
Function Ucasity(s)
If Len(s) Then
Dim r : Set r = New RegExp
r.Global = True
r.Pattern = "[A-Z]"
Dim m : Set m = r.Execute(s)
Ucasity = m.Count / Len(s)
Else
Ucasity = 0
End If
End Function
Function qq(s) : qq = """" & s & """" : End Function
Dim s
For Each s In Array( _
"UPPERCASE but not ALL OR NOTHING" _
, "UPPERCASE" _
, "pipapo" _
, "UPPERCASEuppercase" _
, "" _
)
WScript.Echo qq(s), CStr(s = UCase(s)), UCasity(s)
Next
output:
cscript 39261181.vbs
"UPPERCASE but not ALL OR NOTHING" False 0,65625
"UPPERCASE" True 1
"pipapo" False 0
"UPPERCASEuppercase" False 0,5
"" True 0
Simply use the UCase function
<%
dim a
a = "This is a test 1"
dim b
b = "THIS IS A TEST 2"
If a = ucase(a) then response.write(a & " is all upper")
If b = ucase(b) then response.write(b & " is all upper")
%>
Result
THIS IS A TEST 2 is all upper

Read text file specific string through vbscript

I have text file with multiple line of different jobs jobs status .last run date..etc has been given as below
Jobname=FC;lastdate=12032015;lastresult=0
I need to write out the jobname and lastresult status with "success" for 0 and "fail" for other cases.
As you iterating through the lines of the file (where readline is the variable holding the line we are reading at the time):
jobname= Split(Split(readLine, ";")(0), "=")(1)
if Split(Split(readLine, ";")(2), "=")(1) = 0 Then
lastresult="Success"
else
lastresult="Failure"
end if
Something like this should capture your jobname and lastresult. We are just using SPLIT() to split the string by a delimiter ";" and grabbing the token we need (and then splitting that as well).
Use a Regexp looking for = followed by a sequence of non-; and an array indexed by the comparison between "=0" and the last part of the input line - as in:
>> Set r = New RegExp
>> r.Global = True
>> r.Pattern = "=[^;]+"
>> a = Split("success fail")
>> s = "Jobname=FC;lastdate=12032015;lastresult=0|Jobname=Other;lastdate=12032015;lastresult=Else"
>> For Each s In Split(s, "|")
>> Set ms = r.Execute(s)
>> WScript.Echo Mid(ms(0).Value,2), a(1 + ("=0" = ms(2)))
>> Next
>>
FC success
Other fail

Script won't split line at "=" Delimeter

The script below works in finding duplicates.
But most of the files i'm reading follow this format:
ServerName(1) = "Example1"
ServerName(2) = "Example1"
ServerName(3) = "Example3"
ServerName(4) = "Example4"
ServerName(5) = "Example5"
The 'cut' variable in the code below is supposed to cut the string at the "=" delimiter and return the value that comes after the "=" delimeter.
It should write to the duplicate file "Example1" but instead writes nothing. How would I make it so that the script below reads a file and only finds the duplicate in values after the "=" delimeter.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
FileName = "Test.txt"
PathToSave = "C:"
Path = (PathToSave & FileName)
Set objFile = objFSO.OpenTextFile(Path, ForReading)
Set objOutputFile = objFSO.OpenTextFile(PathToSave & "Noduplicates.txt", 2, True)
Set objOutputFile2 = objFSO.OpenTextFile(PathToSave & "Duplicates.txt", 2, True)
objOutputFile.WriteLine ("This document contains the " & path & " file without duplicates" & vbcrlf)
objOutputFile2.WriteLine ("This document contains the duplicates found. Each line listed below had a duplicate in " & Path & vbcrlf)
Dim DuplicateCount
DuplicateCount = 0
Set Dict = CreateObject("Scripting.Dictionary")
Do until objFile.atEndOfStream
strCurrentLine = LCase(Trim(objFile.ReadLine))
Cut = Split(strCurrentline,"=")
If not Dict.Exists(LCase(Trim(cut(strCurrentLine)))) then
objOutputFile.WriteLine strCurrentLine
Dict.Add strCurrentLine,strCurrentLine
Else Dict.Exists(LCase(Trim(cut(strCurrentLine))))
objOutputFile2.WriteLine strCurrentLine
DuplicateCount = DuplicateCount + 1
End if
Loop
If DuplicateCount > 0 then
wscript.echo ("Number of Duplicates Found: " & DuplicateCount)
Else
wscript.echo "No Duplicates found"
End if
Cut is your array, so Cut(1) is the portion after the =. So that's what you should test for in your dictionary.
If InStr(strCurrentline, "=") > 0 Then
Cut = Split(strCurrentline,"=")
If Not Dict.Exists(Cut(1)) then
objOutputFile.WriteLine strCurrentLine
Dict.Add Cut(1), Cut(1)
Else
objOutputFile2.WriteLine strCurrentLine
DuplicateCount = DuplicateCount + 1
End if
End If
I makes no sense at all to ask Split to return an array with one element by setting the 3rd parameter to 1, as in
Cut = Split(strCurrentline,"=",1)
Evidence:
>> WScript.Echo Join(Split("a=b", "=", 1), "*")
>>
a=b
>> WScript.Echo Join(Split("a=b", "="), "*")
>>
a*b
BTW: ServerName(5) = "Example5" should be splitted on " = "; further thought about the quotes may be advisable.
Update wrt comments (and downvotes):
The semantics of the count parameter according to the docs:
count
Optional. Number of substrings to be returned; -1 indicates that all substrings are returned. If omitted, all substrings are returned.
Asking for one element (not an UBound!) results in one element containing the input.
Evidence wrt the type mismatch error:
>> cut = Split("a=b", "=", 1)
>> WScript.Echo cut
>>
Error Number: 13
Error Description: Type mismatch
>>
So please think twice.

QTP: Checking If an array of strings contains a value

I am having trouble getting my test case to run correctly.
The problem is in the code below, the first if statement to be exact. QTP complains that an object is required
For j=Lbound(options) to Ubound(options)
If options(j).Contains(choice) Then
MsgBox("Found " & FindThisString & " at index " & _
options.IndexOf(choice))
Else
MsgBox "String not found!"
End If
Next
When I check the array I can see that it is populated correctly and 'j' is also the correct string.
Any help with this issue would be greatly appreciated.
Strings in VBScript are not objects, in that they do not have member functions. Searching for a substring should be done by using the InStr function.
For j=Lbound(options) to Ubound(options)
If InStr(options(j), choice) <> 0 Then
MsgBox("Found " & choice & " at index " & j
Else
MsgBox "String not found!"
End If
Next
A concise way to check if an array of strings contains a value would be to combine the Filter and UBound functions:
If Ubound(Filter(options, choice)) > -1 Then
MsgBox "Found"
Else
MsgBox "Not found!"
End If
Cons: you don't get the indexes where the elements are found
Pros: it's simple and you have the usual include and compare parameters to specify the matching criteria.
Function CompareStrings ( arrayItems , choice )
For i=Lbound(arrayItems) to Ubound(arrayItems)
' 0 - for binary comparison "Case sensitive
' 1 - for text compare not case sensitive
If StrComp(arrayItems(i), choice , 0) = 0 Then
MsgBox("Found " & choice & " at index " & i
Else
MsgBox "String not found!"
End If
Next
End Function
Hi if you check exact String not sub-String in the array use StrComb because if use InStr then if array = "apple1" , "apple2" , "apple3" , "apple" and choice = "apple" then all will return pass for every array item.
Function CompareStrings ( arrayItems , choice )
For i=Lbound(arrayItems) to Ubound(arrayItems)
' 1 - for binary comparison "Case sensitive
' 0 - not case sensitive
If StrComp(arrayItems(i), choice , 1) = 0 Then
CompareStrings = True
MsgBox("Found " & choice & " at index " & i
Else
CompareStrings = False
MsgBox "String not found!"
End If
Next
End Function

Resources