Skip to content

Commit 035ec85

Browse files
committed
feat: new function - desensitizePhone
1 parent 7e87c1e commit 035ec85

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ pnpm add @utopia-utils/dom
131131
* formatterPhoneNumber: 手机号格式化。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/stringFormatter.ts)
132132
* formatterIdCard: 身份证呈格式化。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/stringFormatter.ts)
133133
* desensitizeName: 姓名脱敏。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/stringDesensitize.ts)
134+
* desensitizePhone: 手机号脱敏。[source](https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/stringDesensitize.ts)
134135

135136
### 类型判断
136137

packages/core/src/stringDesensitize.test.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { describe, expect, vi } from 'vitest'
1+
import { describe, expect, it } from 'vitest'
22

3-
import { desensitizeName } from './stringDesensitize'
3+
import { desensitizeName, desensitizePhone } from './stringDesensitize'
44

55
describe('stringDesensitize', () => {
66
it('desensitizeName', () => {
@@ -12,4 +12,10 @@ describe('stringDesensitize', () => {
1212
expect(desensitizeName('张二三丰')).toMatchInlineSnapshot(`"张**丰"`)
1313
expect(desensitizeName('张二三四丰')).toMatchInlineSnapshot(`"张***丰"`)
1414
})
15+
16+
it('desensitizePhone', () => {
17+
expect(desensitizePhone()).toBeUndefined()
18+
expect(desensitizePhone('')).toBe('')
19+
expect(desensitizePhone('12345678910')).toMatchInlineSnapshot(`"123****8910"`)
20+
})
1521
})

packages/core/src/stringDesensitize.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,22 @@ export function desensitizeName(name?: string) {
2929

3030
return name[0] + '*'.repeat(length - 2) + name[length - 1]
3131
}
32+
33+
/**
34+
* Desensitizes a phone number by replacing the middle digits with asterisks.
35+
* @param phone - The phone number to desensitize.
36+
* @returns The desensitized phone number.
37+
* @example
38+
* ```ts
39+
* desensitizePhone('12345678910') // '123****8910'
40+
* desensitizePhone('') // ''
41+
* desensitizePhone(undefined) // undefined
42+
* ```
43+
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/core/src/stringDesensitize.ts
44+
*/
45+
export function desensitizePhone(phone?: string) {
46+
if (!isString(phone))
47+
return phone
48+
49+
return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
50+
}

0 commit comments

Comments
 (0)