Skip to content

Commit

Permalink
feat(getStringByteLength): 新增 getStringByteLength 方法,获取字符串的字节长度
Browse files Browse the repository at this point in the history
  • Loading branch information
simonwong committed Mar 22, 2023
1 parent 5daa108 commit eb35240
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/getStringByteLength.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* 获取字符串的 UTF-8 子节长度
*
* @param str - 字符串
* @param index - unicode 的下标
* @returns 字节长度
*
* @example
* ```ts
* getStringByteLength(‘ABC’) // 3
* getStringByteLength(‘哈喽’) // 6
* ```
* @see [Stack Overflow: String length in bytes in JavaScript](https://stackoverflow.com/questions/5515869/string-length-in-bytes-in-javascript)
* @beta
*/
export const getStringByteLength = (str: string) =>
new TextEncoder().encode(str).length
45 changes: 45 additions & 0 deletions test/getStringByteLength.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import assert from 'assert'
import { TextEncoder } from 'util'
import { getStringByteLength } from '../src/getStringByteLength'

global.TextEncoder = TextEncoder

describe('getStringByteLength:', () => {
/**
* number and letter
*/
describe('number and letter', () => {
test(' "123" => 3 ', () => {
assert.strictEqual(getStringByteLength('123'), 3)
})
test(' "ABC" => 3 ', () => {
assert.strictEqual(getStringByteLength('ABC'), 3)
})
})

/**
* Chinese
*/
describe('Chinese', () => {
test(' "哈" => 3 ', () => {
assert.strictEqual(getStringByteLength('哈'), 3)
})

test(' "阿斯顿" => 9 ', () => {
assert.strictEqual(getStringByteLength('阿斯顿'), 9)
})
})

/**
* Emoji
*/
describe('Emoji', () => {
test(' "😂" => 4 ', () => {
assert.strictEqual(getStringByteLength('😂'), 4)
})

test(' "👨‍👩‍👦" => 18 ', () => {
assert.strictEqual(getStringByteLength('👨‍👩‍👦'), 18)
})
})
})

0 comments on commit eb35240

Please sign in to comment.