Skip to content

Commit

Permalink
fix(NumberFormat): improve regex for parsing phone numbers with count…
Browse files Browse the repository at this point in the history
…ry codes
  • Loading branch information
tujoworker committed Nov 25, 2024
1 parent 0b02b6e commit f25e0d0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 17 deletions.
30 changes: 14 additions & 16 deletions packages/dnb-eufemia/src/components/number-format/NumberUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -590,26 +590,24 @@ export const formatPhone = (number, locale = null) => {

switch (locale) {
default: {
// cleanup
number = String(number).replace(/[^+0-9]/g, '')

let code = ''
if (
number.length > 8 &&
number.substring(0, 2) !== '00' &&
!number.startsWith('+')
) {
number = '+' + number
}
number = String(number)
.replace(/^(00|\+)47([^\s])/, '+47 $2') // Edge case for when a Norwegian number is given without a space after the country code
.replace(/^00/, '+')

if (number[0] === '+') {
code = number.substring(0, 3) + ' '
number = number.substring(3)
} else if (number.substring(0, 2) === '00') {
code = number.substring(0, 4) + ' '
number = number.substring(4)
// Get the code and number from a number like this with a regex: +1 23456789
const codeAndNumber = number.match(
/^\+(\d{1,4})\s{0,2}([\d-]{1,20})$/
)
if (codeAndNumber) {
code = `+${codeAndNumber[1]} `
number = codeAndNumber[2]
}
}
code = code.replace(/^00/, '+')

// Remove all non-numeric characters
number = number.replace(/[^+0-9]/g, '')
const length = number.length

// get 800 22 222
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -941,12 +941,30 @@ describe('formatPhone', () => {
expect(number).toBe('12 34 56 78')
})

it('should format a phone number with country code', () => {
it('should format a phone number with country code without space', () => {
const result = formatPhone('+4712345678')
expect(result.number).toBe('+47 12 34 56 78')
expect(result.aria).toBe('+47 12 34 56 78')
})

it('should format a phone number with country code', () => {
const result = formatPhone('+47 12345678')
expect(result.number).toBe('+47 12 34 56 78')
expect(result.aria).toBe('+47 12 34 56 78')
})

it('should format a phone number with single country code', () => {
const result = formatPhone('+1 23456789')
expect(result.number).toBe('+1 23 45 67 89')
expect(result.aria).toBe('+1 23 45 67 89')
})

it('should format a phone number with three country code digits', () => {
const result = formatPhone('+358 23456789')
expect(result.number).toBe('+358 23 45 67 89')
expect(result.aria).toBe('+358 23 45 67 89')
})

it('should format a phone number without country code', () => {
const result = formatPhone('12345678')
expect(result.number).toBe('12 34 56 78')
Expand Down

0 comments on commit f25e0d0

Please sign in to comment.