Skip to content

Commit

Permalink
feat: new function - desensitizePhone
Browse files Browse the repository at this point in the history
  • Loading branch information
GreatAuk committed May 24, 2024
1 parent 7e87c1e commit 035ec85
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ pnpm add @utopia-utils/dom
* formatterPhoneNumber: 手机号格式化。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/stringFormatter.ts)
* formatterIdCard: 身份证呈格式化。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/stringFormatter.ts)
* desensitizeName: 姓名脱敏。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/stringDesensitize.ts)
* desensitizePhone: 手机号脱敏。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/stringDesensitize.ts)

### 类型判断

Expand Down
10 changes: 8 additions & 2 deletions packages/core/src/stringDesensitize.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, vi } from 'vitest'
import { describe, expect, it } from 'vitest'

import { desensitizeName } from './stringDesensitize'
import { desensitizeName, desensitizePhone } from './stringDesensitize'

describe('stringDesensitize', () => {
it('desensitizeName', () => {
Expand All @@ -12,4 +12,10 @@ describe('stringDesensitize', () => {
expect(desensitizeName('张二三丰')).toMatchInlineSnapshot(`"张**丰"`)
expect(desensitizeName('张二三四丰')).toMatchInlineSnapshot(`"张***丰"`)
})

it('desensitizePhone', () => {
expect(desensitizePhone()).toBeUndefined()
expect(desensitizePhone('')).toBe('')
expect(desensitizePhone('12345678910')).toMatchInlineSnapshot(`"123****8910"`)
})
})
19 changes: 19 additions & 0 deletions packages/core/src/stringDesensitize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,22 @@ export function desensitizeName(name?: string) {

return name[0] + '*'.repeat(length - 2) + name[length - 1]
}

/**
* Desensitizes a phone number by replacing the middle digits with asterisks.
* @param phone - The phone number to desensitize.
* @returns The desensitized phone number.
* @example
* ```ts
* desensitizePhone('12345678910') // '123****8910'
* desensitizePhone('') // ''
* desensitizePhone(undefined) // undefined
* ```
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/stringDesensitize.ts
*/
export function desensitizePhone(phone?: string) {
if (!isString(phone))
return phone

return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

0 comments on commit 035ec85

Please sign in to comment.