2

I'm writing a script in VBscript and I need to check if a string is empty or has only white-space characters (such as space, tab, newline, ...)

In .Net there is this convenient string.IsNullOrWhiteSpace() operation to test that, but I can't seem to find an easy equivalent in VBscript.
I know I could loop each character and then compare that to a list of known white-space character, or I could use regular expressions, but I was hoping for a better solution

Geert Bellekens
  • 12,788
  • 2
  • 23
  • 50

2 Answers2

2

There is no such method, i think this is the easiest:

Len(Trim(str)) = 0

As noted by omegastripes this approach is not the same as the .NET method IsNullOrWhieSpace because white-spaces include spaces, tabs, new-lines and other characters of those categories.

There is no equivalent in VbScript. So you need a regex approach if you want to include all characters not only spaces. Here's is one.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Thanks to the answer from Tim I came up with this solution.
It's not perfect, and also not the best answer, but it is good enough for my purpose.

'checks if this string is empty or has only whitespace characters
function isEmptyOrWhiteSpace(stringToCheck)
    dim returnValue
    returnValue = false
    if len(stringToCheck) = 0 then
        returnValue = true
    elseif len(trim(stringToCheck)) = 0 then
        returnValue = true
    else
        'remove all whitespace characters other then spaces
        dim replacedString
        replacedString = replace(stringToCheck, vbTab, "")
        replacedString = replace(replacedString, vbNewline, "")
        replacedString = replace(replacedString, vbCRLF, "")
        'Other characters to replace?
        if len(trim(replacedString)) = 0 then
            returnValue = true
        end if
    end if
    'return
    isEmptyOrWhiteSpace = returnValue
end function
Geert Bellekens
  • 12,788
  • 2
  • 23
  • 50