diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 39bef94..2ba2bf2 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -37,6 +37,7 @@ export * from './randomString' export * from './retry' export * from './sleep' export * from './sort' +export * from './stringFormatter' export * from './union' export * from './unique' export * from './uniqueWith' diff --git a/packages/core/src/stringFormatter.test.ts b/packages/core/src/stringFormatter.test.ts new file mode 100644 index 0000000..fce22b6 --- /dev/null +++ b/packages/core/src/stringFormatter.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest' + +import { formatterBankCard } from './stringFormatter' + +describe('stringFormatter', () => { + it('formatterBankCard', () => { + expect(formatterBankCard('1234567890123456')).toMatchInlineSnapshot(`"1234 5678 9012 3456"`) + expect(formatterBankCard(' 1234 56 7890 23456')).toMatchInlineSnapshot(`"1234 5678 9023 456"`) + expect(formatterBankCard('_ 3232 32432 32432 ')).toMatchInlineSnapshot(`"3232 3243 2324 32"`) + expect(formatterBankCard('_ Sdj 32 32432 jds3232ds ')).toMatchInlineSnapshot(`"3232 4323 232"`) + expect(formatterBankCard('')).toMatchInlineSnapshot(`""`) + expect(formatterBankCard('null')).toMatchInlineSnapshot(`""`) + // @ts-expect-error test undefined + expect(formatterBankCard(undefined)).toMatchInlineSnapshot(`""`) + }) +}) diff --git a/packages/core/src/stringFormatter.ts b/packages/core/src/stringFormatter.ts new file mode 100644 index 0000000..1236ce0 --- /dev/null +++ b/packages/core/src/stringFormatter.ts @@ -0,0 +1,8 @@ +/** + * Formats a bank card number by removing non-digit characters and adding spaces every four digits. + * @param str - The bank card number to be formatted. + * @returns The formatted bank card number. + */ +export function formatterBankCard(str: string) { + return `${str}`.replace(/\D/g, '').replace(/(\d{4})(?=\d)/g, '$1 ') +}