How to trim words inside a text line (QTP, VBScript)
Parent page: Service Functions – String (QTP, VBScript)
Question
The question was asked here.
What QTP function i can use to trim inside string? For e.g. “text text text text” – i want only 1 space between.
Answer
I believe the sample string provided in the question originally contained multiple space characters inside but was already “trimmed” by HTML parser. Anyway, there is no such function in QTP but the goal could be achieved in a variety of ways.
Description
1. Scan for space characters and replace them
2. Split the whole string and reconstruct it
3. Use Regular Expression
Implementation
1. Replace
sLine = "text text text text text " sLine = trim(sLine) Do While InStr(sLine, " ") > 0 sLine = Replace(sLine, " ", " ") Loop
2. Split
sLine = "text text text text text " dvLine = Split(sLine, " ") sLine = dvLine(0) For Iter = 1 To UBound(dvLine) If Trim(dvLine(Iter)) <> "" Then sLine = sLine & " " & dvLine(Iter) End If Next
3. RegEx
Public Function ReplaceEx(ByVal sSource, ByVal sPattern, ByVal sDest, ByVal boolMatchCase) Dim objRegExp Set objRegExp = new RegExp objRegExp.Global = TRUE objRegExp.IgnoreCase = Not boolMatchCase objRegExp.Pattern = sPattern ReplaceEx = objRegExp.Replace(sSource, sDest) Set objRegExp = Nothing End Function sLine = "text text text text text " sResult = ReplaceEx(sLine, " *", " ", False)