引入
ts
import {
getRandomString,
checkStringLength,
randomString,
replaceAllPolyfill,
camelize,
hyphenate,
capitalize,
titleize,
lowerInitial,
pascalCase,
toUnicodeAt,
toUnicode
} from 't-comm';
// 不支持 tree-shaking 的项目
import {
getRandomString,
checkStringLength,
randomString,
replaceAllPolyfill,
camelize,
hyphenate,
capitalize,
titleize,
lowerInitial,
pascalCase,
toUnicodeAt,
toUnicode
} from 't-comm/lib/base/string/index';
// 只支持 ESM 的项目
import {
getRandomString,
checkStringLength,
randomString,
replaceAllPolyfill,
camelize,
hyphenate,
capitalize,
titleize,
lowerInitial,
pascalCase,
toUnicodeAt,
toUnicode
} from 't-comm/es/base/string/index';
getRandomString
描述:
获取随机字符串
参数:
参数名 | 类型 | 描述 |
---|---|---|
length | number | 字符串长度,默认 32 |
返回: string
字符串
示例
ts
randomString()
randomString(16)
checkStringLength(str, [num])
描述:
检查字符串长度
参数:
参数名 | 类型 | 默认值 | 描述 |
---|---|---|---|
str | string | 字符串 | |
[num] | number | 30 | 长度 |
示例
typescript
checkStringLength('123', 2) // true
checkStringLength('123', 3) // true
checkStringLength('123', 4) // false
randomString(length)
描述:
获取随机字符串
参数:
参数名 | 类型 | 描述 |
---|---|---|
length | number | 字符串长度,默认 32 |
返回: string
字符串
示例
ts
randomString()
randomString(16)
replaceAllPolyfill()
描述:
polyfill for replaceAll
参数:
示例
typescript
replaceAllPolyfill()
camelize(str, handleSnake)
描述:
横线转驼峰命名,如果第一个字符是字母,则不处理。
参数:
参数名 | 类型 | 描述 |
---|---|---|
str | string | 输入字符串 |
handleSnake | boolean | 是否处理下划线,默认不处理 |
返回: string
处理后的字符串
示例
typescript
camelize('ab-cd-ef')
// => abCdEf
hyphenate(str)
描述:
驼峰命名转横线命名:拆分字符串,使用 - 相连,并且转换为小写
参数:
参数名 | 类型 | 描述 |
---|---|---|
str | string | 输入字符串 |
返回: string
处理后的字符串
示例
typescript
hyphenate('abCd')
// => ab-cd
capitalize(str)
描述:
字符串首位大写
参数:
参数名 | 类型 | 描述 |
---|---|---|
str | string | 输入字符串 |
返回: string
处理后的字符串
示例
typescript
capitalize('abc')
// => Abc
titleize(str)
描述:
将每个单词的首字母转换为大写
参数:
参数名 | 类型 | 描述 |
---|---|---|
str | string | 输入字符串 |
返回: string
处理后的字符串
示例
typescript
titleize('my name is yang')
// My Name Is Yang
titleize('foo-bar')
// Foo-Bar
lowerInitial(str)
描述:
首字母小写
参数:
参数名 | 类型 | 描述 |
---|---|---|
str | string | 输入字符串 |
返回: string
输出字符串
示例
typescript
lowerInitial('GroupId')
// groupId
pascalCase(str)
描述:
用大驼峰,即 PascalCase 格式,来格式化字符串
参数:
参数名 | 描述 |
---|---|
str | 字符串 |
返回:
PascalCase 的字符串
示例
ts
pascalCase('ab-cd')
// AbCd
pascalCase('ab_cd')
// AbCd
toUnicodeAt(str, index)
描述:
获取字符串指定下标的 unicode
参数:
参数名 | 类型 | 描述 |
---|---|---|
str | string | 字符串 |
index | number | unicode 的下标 |
返回: string
data
示例
typescript
unicodeAt('ABC', 1)
// -> '\\u0042'
toUnicode(str)
描述:
获取字符串的 unicode
参数:
参数名 | 类型 | 描述 |
---|---|---|
str | string | 字符串 |
返回: string
data
示例
typescript
toUnicode('ABC')
// -> '\\u0041\\u0042\\u0043'