I'm new to vbscript and Stack Overflow, and could really use some help.
Currently I'm trying to format a phone number that is read from an image and stored in a variable. Because the images are "dirty" extra characters find their way in, such as periods or parenthesis. I've already restricted the field as much as possible to help prevent picking up extra characters, but alas!
For example I want to turn ",123.4567890" into "123 456 7890" (not including the double quotes). Trouble is I won't know what extra characters could potentially be picked up, ruling out a simple replace.
My logic is remove any non numeric characters, start from the left, insert a space after the third number, insert a space after the sixth number.
Any help would be great, and please feel free to ask for more information if needed.
Use the String. substring() method to remove the first N characters from a string, e.g. const result = str. substring(N) . The substring method will return a new string that doesn't contain the first N characters of the original string.
The Mid function returns a specified number of characters from a string. Tip: Use the Len function to determine the number of characters in a string.
The InStr Function returns the first occurrence of one string within another string. The search happens from left to right.
Welcome to Stack Overflow. You can remove non-digits using Regex, and concatenate the parts using Mid function.
For example:
Dim sTest
sTest = ",123.4567890"
With (New RegExp)
.Global = True
.Pattern = "\D" 'matches all non-digits
sTest = .Replace(sTest, "") 'all non-digits removed
End With
WScript.Echo Mid(sTest, 1, 3) & " "& Mid(sTest, 4, 3) & " "& Mid(sTest, 7, 4)
Or fully using Regex (via a second grouping pattern):
Dim sTest
sTest = ",123.4567890"
With (New RegExp)
.Global = True
.Pattern = "\D" 'matches all non-digits
sTest = .Replace(sTest, "") 'all non-digits removed
.Pattern = "(.{3})(.{3})(.{4})" 'grouping
sTest = .Replace(sTest, "$1 $2 $3") 'formatted
End With
WScript.Echo sTest
Use a first RegExp to clean non-digits from the input and second one using groups for the layout:
Function cleanPhoneNumber( sSrc )
Dim reDigit : Set reDigit = New RegExp
reDigit.Global = True
reDigit.Pattern = "\D"
Dim reStruct : Set reStruct = New RegExp
reStruct.Pattern = "(.{3})(.{3})(.+)"
cleanPhoneNumber = reStruct.Replace( reDigit.Replace( sSrc, "" ), "$1 $2 $3" )
End Function ' cleanPhoneNumber
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With