VBScript Scripting Techniques > Data > Strings
Sometimes I need to display results in columns. Using tabs may help but isn't exactly "fail-safe".
For that reason I wrote the VBScript functions LeftPad and RightPad.
Some examples to explain their usage:
myString = "ABCDEF"
WScript.Echo Left( myString, 3 )
WScript.Echo Left( myString, 9 )
will display:
ABC
ABCDEF
myString = "ABCDEF"
WScript.Echo LeftPad( myString, 3, "+" )
WScript.Echo LeftPad( myString, 9, "+" )
will display:
ABC
ABCDEF+++
LeftPad will often be used to pad strings with spaces.
RightPad is LeftPad's counterpart:
myString = "ABCDEF"
WScript.Echo Right( myString, 3 )
WScript.Echo Right( myString, 9 )
will display:
DEF
ABCDEF
myString = "ABCDEF"
WScript.Echo RightPad( myString, 3, "+" )
WScript.Echo RightPad( myString, 9, "+" )
will display:
ABC
+++ABCDEF
RightPad will often be used to pad numbers (in strings) with zeroes.
Look at this combination:
Dim arrName(1)
Dim arrAge(1)
arrName(0) = "John Doe"
arrName(1) = "Vanessa James"
arrAge(0) = 9
arrAge(1) = 65
WScript.Echo LeftPad( "NAME:", 20, " " ) & RightPad( "AGE:", 4, " " )
For i = 0 To UBound( arrName )
WScript.Echo LeftPad( arrName(i), 20, " " ) & RightPad( arrAge(i), 4, " " )
Next
will display:
NAME: AGE:
John Doe 9
Vanessa James 65
LeftPad, optionally combined with RightPad, is perfect for displaying lists, e.g. WMI class properties and their values.
VBScript code:
Function LeftPad( strText, intLen, chrPad )
'LeftPad( "1234", 7, "x" ) = "1234xxx"
'LeftPad( "1234", 3, "x" ) = "123"
LeftPad = Left( strText & String( intLen, chrPad ), intLen )
End Function
Function RightPad( strText, intLen, chrPad )
'RightPad( "1234", 7, "x" ) = "xxx1234"
'RightPad( "1234", 3, "x" ) = "234"
RightPad = Right( String( intLen, chrPad ) & strText, intLen )
End Function
[Back to the top of this page]