Search code examples
vbscriptsplithp-uft

vbScript ignore many blank spaces after split


When I split a string with many spaces, is there a way to skip blank spaces?

Example string below:

Lorem                            ipsum dolor sit amet, consectetur
             adipiscing elit. Morbi cursus quam sapien, sed ultricies diam vestibulum ac.
Morbi                    luctus nisl eleifend                    mi tincidunt, 
sed vehicula magna lobortis. 

When split, the array contains many positions of " " (blank spaces)

[0] Lorem
[1] " "
[2] " "
[3] " "
[4] " "
[5] Ipsum

So, is there a way to skip this blank spaces and get something like this?

[0] Lorem
[1] Ipsum
[3] dolor

Here's my code:

strTmp = split(tmpstr," ")
For each text in strTmp
'Here I validate other things
  If InStr(x,textToFind) Then
    print "text found"
  Else
    print "not found"
  End If
Next

Solution

  • One of the way is to process the string before splitting it.

    Sample Code

    varStr = "Lorem                            ipsum dolor sit amet, consectetur             adipiscing elit. Morbi cursus quam sapien, sed ultricies diam vestibulum ac. Morbi                    luctus nisl eleifend                    mi tincidunt, sed vehicula magna lobortis"
    
    ' this is what you are getting right now
    arrStr = Split(varStr, " ")
    
    Set objRegEx = CreateObject("VBScript.RegExp")
    With objRegEx
        .Global = True
        .MultiLine = True
        .Pattern = "\s+" 'matches any whitespace character
        varStr1 = objRegEx.Replace(varStr, "¬")
    End With
    Set objRegEx = Nothing
    
    ' this is what you want
    arrStr1 = Split(varStr1, "¬")
    

    I have first stripped all spaces and replaced it with a single ¬ which will act as a delim when I split the string later on.