Formatting 1234567890 to (123) 456 7890

Hello,

I have this string “1234567890” and I would like to format it to “(123) 456 7890”

Kindly assist.

Thanks.

Lennox

This is what I came up with and it works, but there must be a better way:

ThisCallerID = “1234567890”
Dim AreaCode, TheLast7, TheLast4, Thefirst3 as string
AreaCode = “(” + ThisCallerID.Left(3) + “)”
TheLast7 = ThisCallerID.Right(7)
Thefirst3 = TheLast7.Left(3)
TheLast4 = ThisCallerID.Right(4)

ThisCallerID = AreaCode + " " + Thefirst3 + " " + TheLast4
msgbox ThisCallerID

That’s pretty good. You could shorten it a little using Mid. But if this works, I say use it.

There is nothing built in that will format it. You have to do it manually, as you have done. You could probably compress that code somewhat.

ThisCallerID = "1234567890"
ThisFormattedID = "(" + ThisCallerID.Left(3) + ") " + ThisCallerID.Middle(3,3)+ " " + ThisCallerID.Right(4)

I would make it a function and use String.Middle() like this:

function formatPhoneNumber(x as string) as String
    return "(" + x.left(3) + ")" + " " + x.middle(3,3) + " " + x.right(4)
end function

Thanks everyone,
I like Tim’s solution
Thanks again.
Lennox

Var tests() As String = Array("567890", "4567890",_
"34567890", "234567890", "1234567890")
Var s As String

For i As Integer = 0 to tests.LastIndex
  
  s = tests(i)
  
  System.DebugLog If(s.Length>7,"("+s.Left(s.Length-7)+") ", "")+_
  s.Middle(s.Length-7,3)+" "+s.Right(4)
  
Next

App.DoEvents // assure debug messages

Quit

From Norm:

Dim orig As String = "1234567890"
Dim i As Integer = val(orig)
Dim s As String = Format(i, "\(###\)###\-####")
2 Likes

Thanks… not quite.

Dim orig As String = “1234567890”
Dim i As Integer = val(orig)
Dim s As String = Format(i, “(###)\ ###\ ####”)
msgbox s

This won’t work for strings that start with zero.

1 Like

Also phonewords as (99) 800 RENT

OK, Thanks for the info

I don’t think valid phone numbers can start with 0 but if that is the case just change # with 0 on the format.

Not sure where the user intend to use his code, but I know some numbers starting with zero, specially company numbers or area codes. Also there are places with area codes with variable number of digits, like (230) and (65) , (65) not (065). Storing a variable number of digits and handling them as chars can be the best way for those places.

I like to use RegEx for such things.

As a starting point, here’s something created using RegExRX:

dim rx as new RegEx
rx.SearchPattern = "(?msi-U)([0-9]{3})([0-9]{3})([0-9]+)"
rx.ReplacementPattern = "($1) $2 $3"

dim rxOptions as RegExOptions = rx.Options
rxOptions.ReplaceAllMatches = true

dim replacedText as string = rx.Replace( sourceText )