'Remove Tab Spaces in VBScript
I have a delimited string containing tabs, and when I do Trim for the string it is not working. For normal space and double spaces Trim is working properly. Below is my code.
Dim arrStr
arrStr = Split("Customer|Customer Address |Account", "|")
If (Trim(arrStr(1)) = "First Lane") Then
WScript.Echo "Inside If"
End If
WScript.Echo "Outside If"
I tried with LTrim, RTrim and Trim, but nothing works. I also tried writing custom methods to trim tabs like below, but that also does not work. Any help here please?
Function customTrim(str)
Dim re
Set re = New RegExp
re.Pattern = "^\t*"
re.Multiline = False
customTrim = re.Replace(str, "")
End Function
Solution 1:[1]
The builtin functions Trim, LTrim, and RTrim don't remove all whitespace, just regular spaces, hence they won't work for your scenario.
The regular expression you have (^\t*) would only remove leading tabs, but your sample data seems to have trailing tabs. If you want to remove trailing tabs change the expression to \t+$. However, since you probably want to remove all leading/trailing whitespace I'd recommend using ^\s+|\s+$ instead. Note that you also need to set the property Global to True, otherwise only the first match would be removed. The default for the property Multiline is False, so you don't need to explicitly set that.
Function CustomTrim(str)
Set re = New RegExp
re.Pattern = "^\s+|\s+$"
re.Global = True
CustomTrim = re.Replace(str, "")
End Function
Solution 2:[2]
Try this code
varStr = "Customer|Customer Address |Account"
MsgBox CustomTrim(varStr)
Function CustomTrim(str)
Dim re
Set re = New RegExp
re.Pattern = "\t+" '<~~ select one or more tabs
re.Multiline = True
CustomTrim = re.Replace(str, "")
End Function
You used an incorrect regex pattern - you were looking for any tab which is the beginning of string/line (^). You needed to look for one or more tabs wherever they are present in the string.
Solution 3:[3]
str=replace(str,vbTab,"")
I love regex but this is simpler. It will remove leading, trailing and internal tabs. If you only want to remove some tabs, then definitely go the regex route.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ansgar Wiechers |
| Solution 2 | Pankaj Jaju |
| Solution 3 | Ra McLaughlin |
