Skip to content

Commit

Permalink
feat(utils): 新增 toHalfWidthString
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 2, 2022
1 parent fbf58db commit be3ca28
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export * from './sampleIndex'
export * from './selectDom'
export * from './signal'
export * from './swap'
export * from './toHalfWidthString'
export * from './traverse'
export * from './TreeData'
export * from './wait'
Expand Down
13 changes: 13 additions & 0 deletions src/utils/toHalfWidthString.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { toHalfWidthString } from './toHalfWidthString'

describe('toHalfWidthString', () => {
test('ok', () => {
expect(toHalfWidthString(' ')).toBe(' ')
expect(toHalfWidthString('1234567890')).toBe('1234567890')
expect(
toHalfWidthString('abcdefghijklmnopqrstuvwxyz'),
).toBe('abcdefghijklmnopqrstuvwxyz')
expect(toHalfWidthString(',@!#&()%{}')).toBe(',@!#&()%{}')
expect(toHalfWidthString('【】“”。¥×')).not.toBe('[]"".$*')
})
})
20 changes: 20 additions & 0 deletions src/utils/toHalfWidthString.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* 转换为半角字符串。
*
* @param value 要转换的字符串
* @returns 返回转换后的半角字符串
*/
export function toHalfWidthString(value: string): string {
let result = ''
for (let i = 0; i < value.length; i++) {
const charCode = value.charCodeAt(i)
if (charCode === 12288) {
result += String.fromCharCode(charCode - 12256)
} else if (charCode > 65280 && charCode < 65375) {
result += String.fromCharCode(charCode - 65248)
} else {
result += String.fromCharCode(charCode)
}
}
return result
}

0 comments on commit be3ca28

Please sign in to comment.