vbscript 2. String Manipulation Basics


Example

'Base string
Dim exStr : exStr = " <Head>data</Head> "

'Left
Dim res: res = Left(exStr,6) 'res now equals " <Head"
'Right
Dim res: res = Right(exStr,6) 'res now equals "Head> "
'Mid
Dim res: res = Mid(exStr,8,4) 'res now equals "data"
'Replace
Dim res: res = Replace("variable", "var", "") 'res now equals "riable"
'LCase
Dim res: res = Lcase(exStr) 'res now equals " <head>data</head> "
'UCase
Dim res: res = UCase(exStr) 'res now equals " <HEAD>DATA</HEAD> "
'LTrim
Dim res: res = LTrim(exStr) 'res now equals "<Head>data</Head> " notice no space on left side
'RTrim
Dim res: res = RTrim(exStr) 'res now equals "<Head>data</Head> " notice no space on right side
'Trim
Dim res: res = Trim(exStr) 'res now equals "<Head>data</Head>"
'StrReverse
Dim res: res = StrReverse(exStr) 'res now equals " >daeH/<atad>daeH< "
'String
Dim res: res = String(4,"c") 'res now equals "cccc"


'StrComp - String Compare, by default, compares the binary of 2 strings.
'The third parameter allows text comparison, but does not compare case(capitalization). 
'Binary
'-1 = if Binary structure of "cars" < "CARS"
' 0 = if Binary structure of "cars" = "cars"
' 1 = if Binary structure of "CARS" > "cars"
Dim res: res = StrComp("cars", "CARS") 'res now equals -1
Dim res: res = StrComp("cars", "cars") 'res now equals 0
Dim res: res = StrComp("CARS", "cars") 'res now equals 1

'Text
'-1 = if Text structure of "cars" < "CARSSS"
' 0 = if Text structure of "cars" = "cars"
' 1 = if Text structure of "CARSSS" > "cars"
Dim res: res = StrComp("cars", "CARSSS", 1) 'res now equals -1
Dim res: res = StrComp("cars", "cars", 1) 'res now equals 0
Dim res: res = StrComp("CARSSS", "cars", 1) 'res now equals 1

'Space
Dim res: res = "I" & Space(1) & "Enjoy" & Space(1) & "Waffles" 'res now equals "I Enjoy Waffles"

'Instr - Returns position of character or string in the variable.
Dim res: res = Instr(exStr, ">") ' res now equals 6
'InstrRev - Returns position of character or string in the variable from right to left. 
Dim res: res = Instr(exStr, ">") ' res now equals 2

'Split and Join
'These are methods that can be used with strings to convert a string to an array
'or combine an array into a string
Dim res1 : res1 = Split(exStr, ">")
'res1(0) = " <Head"
'res1(1) = "data</Head"
'res1(2) = " "
Dim res2 : res2 = Join(res1, ">")
'res2 now equals " <Head>data</Head> "