Remove Whitespace with VBScript

So I had a line of text in a variable in which I needed to remove some extra whitespace as Split(String,” “) will split at every space. I didn’t want to remove every space, I wanted to leave at least one space. I’ve seen some complicated examples by which they recursively go over the string until they are all gone, or split the array and create a second array removing the empty elements. I found a much simpler method however. It is using our good old friend, regular expression.

sWPString = "This is      a    string        with    extra        whitespace."
Set oRegEx = CreateObject("VBScript.RegExp")
oRegEx.Global = True
oRegEx.Pattern = "\s+"
sNoWPString = oRegEx.Replace(sWPString," ")

Now this will leave a space at the beginning if there was already a space there. You can of course just LTrim that off. And RTrim wouldn’t hurt. Or just Trim it.

Leave a Reply

Your email address will not be published. Required fields are marked *