forked from fairyhunter13/phone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.go
40 lines (34 loc) · 1.11 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package phone
import (
"fmt"
"github.com/nyaruka/phonenumbers"
"regexp"
"strconv"
)
const (
// DefaultCountryCodeNumberID is the default country code number used for parsing using ID.
DefaultCountryCodeNumberID = 62
)
var (
regexPlusLeadingNumber = regexp.MustCompile(`^\+*`)
regexZeroLeadingNumber = regexp.MustCompile(`^\+0+`)
supportedCountryCodes = phonenumbers.GetSupportedCallingCodes()
)
// NormalizeID parses the phone number using the countryCode.
// It returns the normalized phone number and the country code.
// The default country code is ID.
func NormalizeID(phoneNumber string, countryCode int) (res string) {
res = phoneNumber
if countryCode == 0 || !supportedCountryCodes[countryCode] {
countryCode = DefaultCountryCodeNumberID
}
countryCodeStr := strconv.Itoa(countryCode)
phoneNumber = regexPlusLeadingNumber.ReplaceAllString(phoneNumber, "+")
phoneNumber = regexZeroLeadingNumber.ReplaceAllString(phoneNumber, "+"+countryCodeStr)
pn, err := phonenumbers.Parse(phoneNumber, "")
if err != nil {
return
}
res = fmt.Sprintf("%d%d", pn.GetCountryCode(), pn.GetNationalNumber())
return
}