diff --git a/packages/dnb-eufemia/src/components/number-format/NumberUtils.js b/packages/dnb-eufemia/src/components/number-format/NumberUtils.js index fef86cd0218..9be66a65d44 100644 --- a/packages/dnb-eufemia/src/components/number-format/NumberUtils.js +++ b/packages/dnb-eufemia/src/components/number-format/NumberUtils.js @@ -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 diff --git a/packages/dnb-eufemia/src/components/number-format/__tests__/NumberUtils.test.ts b/packages/dnb-eufemia/src/components/number-format/__tests__/NumberUtils.test.ts index 6acdbc6d9b4..b130b4259bc 100644 --- a/packages/dnb-eufemia/src/components/number-format/__tests__/NumberUtils.test.ts +++ b/packages/dnb-eufemia/src/components/number-format/__tests__/NumberUtils.test.ts @@ -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')