Last active
February 11, 2025 10:24
-
-
Save gladchinda/db3152c78c86f667a0c34c4e782402c6 to your computer and use it in GitHub Desktop.
Human readable IBAN formatting utility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number | |
const IbanSpecialCountries = ['BI', 'EG', 'LY', 'SV'] as const; | |
// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number | |
const IbanBreakpointsRegex = { | |
// Breaks after every 4th character | |
// Example: XXXX XXXX XXXX XXXX XXXX XX.. | |
default: /([a-z\d]{4}(?!$))/gi, | |
// Burundi (4 5 5 11 2) | |
// Example: BIXX XXXXX XXXXX XXXXXXXXXXX XX | |
BI: /((?=(?:[a-z\d]{23}|[a-z\d]{18}|[a-z\d]{13}|[a-z\d]{2})$))/gi, | |
// Egypt (no spaces) | |
// Example: EGXXXXXXXXXXXXXXXXXXXXXXXXXXX | |
// Uncomment this next line to format with spaces regardless | |
// EG: /((?=(?:[a-z\d]{27}|[a-z\d]{25}|[a-z\d]{21}|[a-z\d]{17})$))/gi, | |
// Libya (4 3 3 15) | |
// Example: LYXX XXX XXX XXXXXXXXXXXXXXX | |
LY: /((?=(?:[a-z\d]{21}|[a-z\d]{18}|[a-z\d]{15})$))/gi, | |
// El Salvador (2 2 4 20) | |
// Example: SV XX XXXX XXXXXXXXXXXXXXXXXXXX | |
SV: /((?=(?:[a-z\d]{26}|[a-z\d]{24}|[a-z\d]{20})$))/gi, | |
} as const satisfies Partial<Record<(typeof IbanSpecialCountries)[number] | 'default'>>; | |
type IbanBreakpointsCountry = keyof typeof IbanBreakpointsRegex; | |
export function getHumanReadableIban(iban: string, useNonBreakingSpaces = true): string { | |
const spaceSeparator = (useNonBreakingSpaces as any) !== false ? ' ' : ' '; | |
const ibanWithoutSpaces = iban.replace(/\s+/g, ''); | |
let breakpointsCountry: IbanBreakpointsCountry = 'default'; | |
for (const country of IbanSpecialCountries) { | |
if (RegExp(`^${country}`, 'i').test(ibanWithoutSpaces)) { | |
breakpointsCountry = country as IbanBreakpointsCountry; | |
break; | |
} | |
} | |
return ibanWithoutSpaces.replace(IbanBreakpointsRegex[breakpointsCountry]!, `$1${spaceSeparator}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment