-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(getStringByteLength): 新增 getStringByteLength 方法,获取字符串的字节长度
- Loading branch information
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
}) | ||
}) | ||
}) |