Options
All
  • Public
  • Public/Protected
  • All
Menu

sheng-tool

一个工具库。

除浏览器相关函数外,单测达到了 100% 覆盖率,覆盖了常用的函数。

文档部署到了 npm 上。点击 unpkg 上的这个链接 可以阅读文档。

Index

数组相关方法 Functions

浏览器相关方法 Functions

浏览器类型判断相关方法 Functions

颜色相关方法 Functions

日期相关方法 Functions

额外方法 Functions

数据格式判断相关方法 Functions

数字相关方法 Functions

对象相关方法 Functions

统计相关方法 Functions

字符串相关方法 Functions

数组相关方法 Functions

Const countOccurrences

  • countOccurrences<T>(arr: T[], value: T): number
  • 检查给定数组中某元素出现的次数,采用 SameValueZero 算法来比较(与 === 的区别为 NaNNaN 相等)。

    example
    countOccurrences([1, 1, 2, 3], 1)                // 2
    countOccurrences(['1', 1, 2, 3], '1')            // 1
    countOccurrences([NaN, true, NaN, [3]], NaN)     // 2
    countOccurrences([], 3)                          // 0
    

    Type parameters

    • T

    Parameters

    • arr: T[]

      被遍历的数组

    • value: T

      目标元素

    Returns number

Const everyNth

  • everyNth<T>(arr: T[], nth: number): T[]
  • 返回数组中指定下标间隔的元素,首先选取第一个元素,然后跳过间隔数 -1 的元素选取下一个,以此类推。

    example
    everyNth([1, 2, 3, 4], 2)    // [1, 3]
    

    Type parameters

    • T

    Parameters

    • arr: T[]

      被遍历的数组

    • nth: number

      指定的下标间隔

    Returns T[]

Const getLabelByValue

  • getLabelByValue<T>(arr: T[], value: any): undefined | NonNullable<T>[keyof T]
  • 在一个对象数组中,根据指定的 value 找对应的 label(如果有多个,返回第一个),如果没找到,返回 undefined

    通常配合组件库的选择器使用。

    example
    getLabelByValue([{ value: 1, label: '1' }, { value: 2, label: '2' }], 1)   // '1'
    getLabelByValue([{ value: 1, label: '1' }, { value: 2, label: '2' }], 3)   // undefined
    

    Type parameters

    • T: { label: any; value: any }

    Parameters

    • arr: T[]

      对象数组

    • value: any

      指定的 value

    Returns undefined | NonNullable<T>[keyof T]

Const getValueByAnotherValue

  • getValueByAnotherValue<T>(arr: T[], key: keyof T, value: any, anotherKey: keyof T): undefined | NonNullable<T>[keyof T]
  • 在一个对象数组中,根据指定的 keyvalue,查找对应的元素(使用深比较,返回第一个),并返回其 anotherKey 对应的值,如果没找到,则返回 undefined

    example
    getValueByAnotherValue([{ a: 1, b: 2 }, { a: 2, b: 3 }], 'a', 2, 'b')   // 3
    getValueByAnotherValue([{ a: 1, b: 2 }, { a: 2, b: 3 }], 'a', 3, 'b')   // undefined
    

    Type parameters

    • T

    Parameters

    • arr: T[]

      对象数组

    • key: keyof T

      要查找的指定的 key

    • value: any

      要查找的指定的 value

    • anotherKey: keyof T

      需要返回的值对应的 key

    Returns undefined | NonNullable<T>[keyof T]

Const getValueByLabel

  • getValueByLabel<T>(arr: T[], label: any): undefined | NonNullable<T>[keyof T]
  • 在一个对象数组中,根据指定的 label 找对应的 value(如果有多个,返回第一个),如果没找到,返回 undefined

    通常配合组件库的选择器使用。

    example
    getValueByLabel([{ value: 1, label: '1' }, { value: 2, label: '2' }], '1')   // 1
    getValueByLabel([{ value: 1, label: '1' }, { value: 2, label: '2' }], '3')   // undefined
    

    Type parameters

    • T: { label: any; value: any }

    Parameters

    • arr: T[]

      对象数组

    • label: any

      指定的 label

    Returns undefined | NonNullable<T>[keyof T]

Const isSubset

  • isSubset<T>(source: T[], target: T[], deep?: boolean): boolean
  • 判断一个数组是否为另一个数组的子集,可通过参数来区分浅比较(SameValueZero)和深比较。

    example
    isSubset([1, 2, 3], [1, 2, 3, 4])            // true
    isSubset([1, 2, 3], [1, 2, 4])               // false
    isSubset([1, 1, 2, 3], [1, 2, 3])            // false
    isSubset([1, 1, 2, 3], [1, 1, 2, 3, 4])      // true
    isSubset([{ x: 1 }], [{ x: 1 }, { x: 2 }])   // true
    isSubset([{ x: 1 }], [{ x: 1 }], false)      // false
    

    Type parameters

    • T

    Parameters

    • source: T[]

      需要判断的数组

    • target: T[]

      被判断的数组

    • deep: boolean = true

      是否深比较,默认为 true

    Returns boolean

Const isUniqItem

  • isUniqItem(arr: any[], deep?: boolean): boolean
  • 判断数组是否包含有相同元素,可通过参数来区分浅比较(此时使用 SameValueZero 算法)和深比较。

    example
    isUniqItem([1, 1, 2, 3])                     // false
    isUniqItem([1, 2, 3])                        // true
    isUniqItem([NaN, NaN])                       // false
    isUniqItem([{ a: 1 }, { a: 1 }])             // false
    isUniqItem([{ a: 1 }, { a: 1 }], false)      // true
    

    Parameters

    • arr: any[]

      要检查的数组

    • deep: boolean = true

      是否深比较,默认为 true

    Returns boolean

浏览器相关方法 Functions

Const copyHTML

  • copyHTML(html: string): any
  • 复制 HTML,一般用于富文本编辑器的场合。

    example
    (async () => {
        const text = await copyHTML('<ul><li>hello</li><li>world</li></ul>');
        // 此时按 Ctrl / Command + V 到富文本编辑器中即可粘贴「hello」和「world」的有序列表
    }
    

    Parameters

    • html: string

      被复制的 HTML 字符串

    Returns any

Const copyText

  • copyText(text: string): Promise<void>
  • 复制文本,兼容 IE9(需要 Promise Polyfill)。

    example
    (async () => {
        const text = await copyText('hello world');
        // 此时按 Ctrl / Command + V 即可粘贴「hello world 文本」
    }
    

    Parameters

    • text: string

      被复制的文本

    Returns Promise<void>

Const elementIsVisibleInViewport

  • elementIsVisibleInViewport(el: Element, partiallyVisible?: boolean): boolean
  • 判断元素是否在浏览器可视范围内,分为部分可见(默认)和完全可见两种情况。

    Parameters

    • el: Element

      被观察的元素

    • partiallyVisible: boolean = false

      该元素是否「完全可见」才符合「可视范围」的标准,默认为 false

    Returns boolean

Const getAsyncValue

  • getAsyncValue<T>(fn: () => T, ms?: number, excludeValues?: (undefined | null)[]): Promise<T>
  • 异步地获取一些值。

    在有些场景时,一些值无法通过同步的方法拿到,甚至异步的方法也不行,只能通过轮询。

    具体也就是说,每隔一段时间(默认 50ms)看一下值有没有获取到,获取到返回包裹该值的 Promise,并就关掉定时器。

    example
    // 在 MVVM 框架中,DOM 会等到数据加载完成之后才渲染,但我们需要在源码之外的地方获取 DOM
    (async () => {
        const dom = await getAsyncValue(() => document.getElementById('app'));
        const attr = dom.getAttribute('something');
        // 处理 attr
    }
    

    Type parameters

    • T = any

    Parameters

    • fn: () => T

      获取值的方法

        • (): T
        • Returns T

    • ms: number = 50

      间隔时间,默认 50ms

    • excludeValues: (undefined | null)[] = ...

      排除值列表,默认为 [null, undefined],只有返回值不在该列表中才认为获取到,使用 includes 方法判断

    Returns Promise<T>

Const getFullUrl

  • getFullUrl(url: string): string
  • 将 URL 片段与当前域名拼合,组成完成 URL。

    example
    // 假设当前域名为 https://www.example.com
    getFullUrl('edit.html?query=1')      // 'https://www.example.com/edit.html?query=1'
    

    Parameters

    • url: string

      URL 片段,为域名后面的内容(不包含开头的斜杠)

    Returns string

Const getQueryString

  • getQueryString(name: string): undefined | string
  • 获取 URL 参数中指定名称对应的值,如果没找到,返回 undefined

    Parameters

    • name: string

      参数名

    Returns undefined | string

Const injectScriptBySrc

  • injectScriptBySrc(src: string, config?: { async?: boolean; defer?: boolean }): Promise<unknown>
  • 动态引入 JS CDN 文件,返回一个 Promise,当加载完毕时为 resolve 状态,加载失败后为 reject

    其中配置的 deferasync 对应 <script> 标签的两种属性。

    example
    try {
        // 插入 Vue 库
        await injectScriptBySrc('https://cdn.bootcdn.net/ajax/libs/vue/3.0.2/vue.global.js');
    
        // 成功插入,接下来可以拿到 Vue 全局变量并操作
        const app = Vue.createApp({});
    } catch (err) {
        // 插入失败
        console.log('加载 Vue 库失败,详情为:' + err.message);
    }
    

    Parameters

    • src: string

      JS 文件地址

    • Optional config: { async?: boolean; defer?: boolean }

      配置

      • Optional async?: boolean

        是否异步加载,默认为 true

      • Optional defer?: boolean

        是否延迟加载,默认为 true

    Returns Promise<unknown>

Const injectScriptByText

  • injectScriptByText(text: string, config?: { async?: boolean; defer?: boolean }): Promise<unknown>
  • 动态引入 JS 字符串,返回一个 Promise,当加载完毕时为 resolve 状态,加载失败后为 reject

    其中配置的 deferasync 对应 <script> 标签的两种属性。

    example
    try {
        // 加载自定义字符串并执行
        await injectScriptByText('var globalVariable = 1');
    
        // 执行成功,接下来可以拿到 globalVariable 全局变量并操作
        console.log(globalVariable);
    } catch (err) {
        // 执行失败
        console.log('代码执行失败' + err.message);
    }
    

    Parameters

    • text: string

      JS 字符串

    • Optional config: { async?: boolean; defer?: boolean }

      配置

      • Optional async?: boolean

        是否异步加载,默认为 true

      • Optional defer?: boolean

        是否延迟加载,默认为 true

    Returns Promise<unknown>

Const preventScroll

  • preventScroll(): () => void
  • 一些业务场景,如弹框出现时,需要禁止页面滚动,这是兼容安卓和 iOS 禁止页面滚动的解决方案。

    该函数返回另一个函数闭包,其存储了当前页面滚动位置,再次执行可以恢复页面状态。

    example
    // ...用户执行一些操作,弹出弹框
    
    // 禁止页面滚动
    const reverseScroll = preventScroll();
    
    // ...用户操作完毕,弹框关闭,页面恢复
    
    // 恢复页面滚动
    reverseScroll();
    

    Returns () => void

      • (): void
      • Returns void

Const scrollToTop

  • scrollToTop(millisecond?: number): void
  • 将页面平滑滚动到顶部。

    Parameters

    • millisecond: number = 1000

      滚动持续的时长(单位为毫秒,默认为 1000)

    Returns void

Const wait

  • wait(milliseconds: number): Promise<void>
  • Promise 形式的等待,等待指定毫秒数后 resolve 空值。

    example
    (async () => {
        console.log(1);      // 输出 1
        await wait(350);     // 等待 350 毫秒
        console.log(2);      // 输出 2
    })();
    

    Parameters

    • milliseconds: number

      毫秒数

    Returns Promise<void>

Const waitForSeconds

  • waitForSeconds(seconds: number): Promise<void>
  • Promise 形式的等待,与 wait 不一样的是,它等待的单位是秒。

    example
    (async () => {
        console.log(1);                  // 输出 1
        await waitForSeconds(1.5);       // 等待 1.5 秒
        console.log(2);                  // 输出 2
    })();
    

    Parameters

    • seconds: number

      秒数

    Returns Promise<void>

浏览器类型判断相关方法 Functions

Const isAndroid

  • isAndroid(): boolean

Const isDeviceMobile

  • isDeviceMobile(): boolean
  • 是否是移动端,原理是检查 UA 中是否包含 androidwebosiphoneipadipodblackberry

    Returns boolean

Const isPC

  • isPC(): boolean

Const isQQBrowser

  • isQQBrowser(): boolean
  • 是否是 QQ 浏览器,原理是检查 UA 中是否包含 mqqbrowserqzoneqqbrowserqbwebviewtype

    Returns boolean

Const isSpider

  • isSpider(): boolean

Const isWeiXin

  • isWeiXin(): boolean

Const isWeiXinMiniProgram

  • isWeiXinMiniProgram(): boolean
  • 是否是微信小程序环境(包括微信开发者工具),原理是检查 UA 中是否包含 miniprogram

    Returns boolean

Const isiOS

  • isiOS(): boolean

颜色相关方法 Functions

Const hex2rgb

  • hex2rgb(hex: string): number[]
  • 将 #RRGGBB 或 #RGB 字符串转换成红、绿、蓝三种颜色分量的数组

    example
    hex2rgb('#193a69')       // [25, 58, 105]
    hex2rgb('#eee')          // [238, 238, 238]
    

    Parameters

    • hex: string

      颜色字符串

    Returns number[]

Const rgb2hex

  • rgb2hex(r: number, g: number, b: number, short?: boolean): string
  • 将传入的红、绿、蓝三种颜色分量转换成标准的 #RRGGBB 字符串,可选是否使用短字符串(#RGB)

    example
    rgb2hex(0, 0, 0)         // '#000000'
    rgb2hex(0, 0, 0, true)   // '#000'
    rgb2hex(25, 58, 105)     // '#193a69'
    

    Parameters

    • r: number

      红色

    • g: number

      绿色

    • b: number

      蓝色

    • short: boolean = false

      默认为 false,是否使用短字符串

    Returns string

日期相关方法 Functions

Const getDatePeriod

  • getDatePeriod(start: Date, finish: Date): number
  • 获取两个日期的间隔天数

    example
    getDatePeriod(new Date('2021/03/28'), new Date('2021/03/29'))    // 1
    

    Parameters

    • start: Date

      起始日期

    • finish: Date

      结束日期

    Returns number

Const getDaysInMonth

  • getDaysInMonth(date?: Date): number
  • 取得指定时间所在月份的天数,如果不传参,则指定当前时间

    example
    getDaysInMonth(new Date('2021/03/01'))     // 31
    getDaysInMonth(new Date('2021/02/05'))     // 28
    getDaysInMonth(new Date('2020/09/03'))     // 30
    getDaysInMonth(new Date('2024/02/08'))     // 29
    

    Parameters

    • date: Date = ...

      指定时间

    Returns number

Const getFirstDateInMonth

  • getFirstDateInMonth(date?: Date): Date
  • 获取指定时间所在月的第一天,如果不传参,则指定当前时间

    example
    getFirstDateInMonth(new Date('2021/03/05'))      // new Date('2021/03/01')
    

    Parameters

    • date: Date = ...

      指定时间

    Returns Date

Const getFirstDateInQuarter

  • getFirstDateInQuarter(date?: Date): Date
  • 获取指定时间所在季度的第一天,如果不传参,则指定当前时间

    example
    getFirstDateInQuarter(new Date('2021/03/28'))    // new Date('2021/01/01')
    

    Parameters

    • date: Date = ...

      指定时间

    Returns Date

Const getLastDateInMonth

  • getLastDateInMonth(date?: Date): Date
  • 获取指定时间所在月的最后一天,如果不传参,则指定当前时间

    example
    getLastDateInMonth(new Date('2021/03/05'))       // new Date('2021/03/31')
    

    Parameters

    • date: Date = ...

      指定时间

    Returns Date

Const getLastDateInQuarter

  • getLastDateInQuarter(date?: Date): Date
  • 获取指定时间所在季度的最后一天,如果不传参,则指定当前时间

    example
    getLastDateInQuarter(new Date('2021/03/28'))    // new Date('2021/03/31')
    

    Parameters

    • date: Date = ...

      指定时间

    Returns Date

Const getWeeksInMonth

  • getWeeksInMonth(date?: Date, firstDayOfWeek?: 0 | 1): 4 | 5 | 6
  • 获取当前月份的周数,取决于每周是从周日开始(默认)还是从周一开始

    example
    getWeeksInMonth(new Date('2021/03/28'))      // 5
    

    Parameters

    • date: Date = ...

      指定时间

    • firstDayOfWeek: 0 | 1 = 0

      若设为 0(默认值),则每周从周日开始,设为 1 则为从周一开始

    Returns 4 | 5 | 6

Const isLeapYear

  • isLeapYear(date?: Date): boolean
  • 判断指定时间是否是闰年,如果不传参,则判断当年

    example
    isLeapYear(new Date('2021/03/01'))     // false
    isLeapYear(new Date('2020/09/03'))     // true
    

    Parameters

    • date: Date = ...

      指定时间

    Returns boolean

额外方法 Functions

Const checkPwdStrong

  • checkPwdStrong(password: string): number
  • 检测密码强度,规则为出现数字、大写字母、小写字母、下划线分别加一分,返回总分。

    example
    checkPwdStrong('1')      // 1
    checkPwdStrong('a')      // 1
    checkPwdStrong('1a')     // 2
    checkPwdStrong('1Aa')    // 3
    checkPwdStrong('1Aa_')   // 4
    

    Parameters

    • password: string

      被检测的密码

    Returns number

Const getRegexpByUrlPattern

  • getRegexpByUrlPattern(pattern: string): RegExp
  • 将 URL Pattern 表达式转成正则表达式,URL Pattern 的语法参考这里

    example
    getRegexpByUrlPattern('*://www.baidu.com/').toString()      // '/^(http|https|file|ftp):\\/\\/www\\.baidu\\.com\\/\\/?/'
    

    Parameters

    • pattern: string

      URL Pattern 字符串

    Returns RegExp

Const numberToChinese

  • numberToChinese(num: number, big?: boolean, prefixZero?: boolean): string
  • 将阿拉伯数字转换成中文数字,可以转换成小写(默认)或大写(银行数字用的那种)。

    example
    numberToChinese(5)           // '五'
    numberToChinese(13)          // '十三'
    numberToChinese(105)         // '一百零五'
    numberToChinese(1234)        // '一千二百三十四'
    numberToChinese(1000001001)  // '十亿零一千零一'
    numberToChinese(80000000)    // '八千万'
    numberToChinese(13, true)    // '拾叁'
    

    Parameters

    • num: number

      被转换的阿拉伯数字

    • big: boolean = false

      是否采用大写数字,默认为 false

    • prefixZero: boolean = false

    Returns string

Const removeHTMLTag

  • removeHTMLTag(str: string): string
  • 去掉 HTML 标签。

    example
    removeHTMLTag('<div>123</div>')      // '123'
    

    Parameters

    • str: string

      要转换的字符串

    Returns string

数据格式判断相关方法 Functions

Const generateNumberValidator

  • generateNumberValidator(max: number, decimalLength?: number, allowMinus?: boolean): (str: string) => boolean
  • 生成一个数字验证器,以验证特殊(不超过特定值及小数点位数)的数字格式。

    example
    generateNumberValidator(50, 2)('hello')        // false
    generateNumberValidator(50)('1.5')             // false
    generateNumberValidator(50, 2)('49.95')        // true
    generateNumberValidator(50, 2)('1.5')          // true
    generateNumberValidator(50, 2)('-1')           // false
    generateNumberValidator(50, 2, true)('-1')     // true
    generateNumberValidator(50, 1)('80')           // false
    generateNumberValidator(50, 1)('30.25')        // false
    

    Parameters

    • max: number

      最大值

    • decimalLength: number = 0

      小数位数,默认为 0

    • allowMinus: boolean = false

      是否允许为负数,默认为 false

    Returns (str: string) => boolean

      • (str: string): boolean
      • Parameters

        • str: string

        Returns boolean

Const is12Time

  • is12Time(str: string): boolean
  • 验证 12 小时制时间格式(hh:mm:ss)。

    example
    is12Time('10:05:35')     // true
    is12Time('20:05:35')     // false
    is12Time('string')       // false
    

    Parameters

    • str: string

    Returns boolean

Const is24Time

  • is24Time(str: string): boolean
  • 验证 24 小时制时间格式(HH:mm:ss)。

    example
    is24Time('10:05:35')     // true
    is24Time('20:05:35')     // true
    is24Time('string')       // false
    

    Parameters

    • str: string

    Returns boolean

Const isAShareCode

  • isAShareCode(str: string): boolean
  • 验证 A 股代码,规则为 sh / sz / SH / SZ 后面跟六位数字。

    example
    isAShareCode('sh001896')     // true
    isAShareCode('sz001896')     // true
    isAShareCode('SH001896')     // true
    isAShareCode('SZ001896')     // true
    

    Parameters

    • str: string

    Returns boolean

Const isBankCardCode

  • isBankCardCode(str: string): boolean
  • 验证银行卡号。

    example
    isBankCardCode('000')                    // false
    isBankCardCode('6212263602033054274')    // true
    

    Parameters

    • str: string

    Returns boolean

Const isBase64

  • isBase64(str: string): boolean
  • 验证 base64 字符串。

    example
    isBase64('data:image/png;base64,iVB')    // true
    

    Parameters

    • str: string

    Returns boolean

Const isCarNumber

  • isCarNumber(str: string): boolean
  • 验证车牌号。

    example
    isCarNumber('浙AD12345')    // true
    isCarNumber('京L50137')     // true
    

    Parameters

    • str: string

    Returns boolean

Const isChinese

  • isChinese(str: string): boolean
  • 验证中文。

    example
    isChinese('你好')        // true
    isChinese('hello')       // false
    

    Parameters

    • str: string

    Returns boolean

Const isChineseName

  • isChineseName(str: string): boolean
  • 验证中文名。

    example
    isChineseName('ming')   // false
    isChineseName('小明')   // true
    

    Parameters

    • str: string

    Returns boolean

Const isDateString

  • isDateString(str: string): boolean
  • 验证日期字符串,允许中间用横杠或点连接。

    example
    isDateString('2021-06-03')       // true
    isDateString('1995.08.06')       // true
    isDateString('2020-05.46')       // false
    

    Parameters

    • str: string

    Returns boolean

Const isEd2kURI

  • isEd2kURI(str: string): boolean
  • 验证 ed2k 地址。

    example
    isEd2kURI('ed2k://|file|C6%A5%A3%A9%60.avi|/')     // true
    

    Parameters

    • str: string

    Returns boolean

Const isEmail

  • isEmail(str: string): boolean
  • 验证邮箱格式

    example
    isEmail('example@hotmail.com')   // true
    

    Parameters

    • str: string

    Returns boolean

Const isEnglish

  • isEnglish(str: string): boolean
  • 验证英文。

    example
    isEnglish('你好')        // false
    isEnglish('hello')       // true
    

    Parameters

    • str: string

    Returns boolean

Const isEnglishLower

  • isEnglishLower(str: string): boolean
  • 验证小写字母。

    example
    isEnglishLower('A')      // false
    isEnglishLower('a')      // true
    

    Parameters

    • str: string

    Returns boolean

Const isEnglishName

  • isEnglishName(str: string): boolean
  • 验证英文名。

    example
    isEnglishName('ming')   // true
    isEnglishName('小明')   // false
    

    Parameters

    • str: string

    Returns boolean

Const isEnglishUpper

  • isEnglishUpper(str: string): boolean
  • 验证大写字母。

    example
    isEnglishUpper('A')      // true
    isEnglishUpper('a')      // false
    

    Parameters

    • str: string

    Returns boolean

Const isIMEI

  • isIMEI(str: string): boolean
  • 验证手机机身码,规则为 15 ~ 17 位数字。

    example
    isIMEI('356737118097895')    // true
    

    Parameters

    • str: string

    Returns boolean

Const isIPv4

  • isIPv4(str: string): boolean
  • 验证 IPv4 地址。

    example
    isIPv4('111.13.140.18')    // true
    

    Parameters

    • str: string

    Returns boolean

Const isIPv6

  • isIPv6(str: string): boolean
  • 验证 IPv6 地址。

    example
    isIPv6('2409:8c00:7821:15:40::3')    // true
    

    Parameters

    • str: string

    Returns boolean

Const isIdentity

  • isIdentity(str: string): boolean
  • 验证身份证号码。

    example
    isIdentity('hello')                  // false
    isIdentity('99048219810811486X')     // false
    isIdentity('41048219811311486X')     // false
    isIdentity('410482810811486')        // true
    isIdentity('41048219810811486X')     // true
    isIdentity('530121198907165303')     // true
    

    Parameters

    • str: string

    Returns boolean

Const isImageURL

  • isImageURL(str: string): boolean
  • 验证图片地址。

    example
    isImageURL('https://ns-strategy.cdn.bcebos.com/ns-strategy/upload/fc_big_pic/part-00211-1923.jpg')   // true
    

    Parameters

    • str: string

    Returns boolean

Const isIntegerString

  • isIntegerString(str: string): boolean
  • 验证整数字符串。

    example
    isIntegerString('0')     // true
    isIntegerString('15')    // true
    isIntegerString('-3')    // true
    isIntegerString('0.5')   // false
    isIntegerString('01')    // false
    

    Parameters

    • str: string

    Returns boolean

Const isJavaPackageName

  • isJavaPackageName(str: string): boolean
  • 验证 Java 包名。

    example
    isJavaPackageName('com.didi.aurora.wk')  // true
    

    Parameters

    • str: string

    Returns boolean

Const isLinuxFileAddress

  • isLinuxFileAddress(str: string): boolean
  • 验证 Linux 文件地址。

    example
    isLinuxFileAddress('/etc/nginx/nginx.conf')      // true
    

    Parameters

    • str: string

    Returns boolean

Const isLinuxFolderAddress

  • isLinuxFolderAddress(str: string): boolean
  • 验证 Linux 文件夹地址。

    example
    isLinuxFolderAddress('/root/')      // true
    

    Parameters

    • str: string

    Returns boolean

Const isLinuxHiddenFileAddress

  • isLinuxHiddenFileAddress(str: string): boolean
  • 验证 Linux 隐藏文件地址。

    example
    isLinuxHiddenFileAddress('/home/vue-test/.gitignore')      // true
    

    Parameters

    • str: string

    Returns boolean

Const isLinuxPath

  • isLinuxPath(str: string): boolean
  • 验证 Linux 路径,包含文件地址和文件夹地址。

    example
    isLinuxPath('/home/')            // true
    isLinuxPath('/home/index.html')  // true
    

    Parameters

    • str: string

    Returns boolean

Const isMD5

  • isMD5(str: string): boolean
  • 验证 md5,规则为 32 位十六进制数字(字母需要全大写或全小写)。

    example
    isMD5('0e37e09b702d2815e32be7c7b65a62da')    // true
    

    Parameters

    • str: string

    Returns boolean

Const isMacAddress

  • isMacAddress(str: string): boolean
  • 验证 MAC 地址,十六进制数字支持大小写(但只能为大写或小写),分隔符支持冒号和横杠。

    example
    isMacAddress('00-16-EA-AE-3C-40')        // true
    isMacAddress('00:16:ea:ae:3c:40')        // true
    

    Parameters

    • str: string

    Returns boolean

Const isMagnetURI

  • isMagnetURI(str: string): boolean
  • 验证磁力链接。

    example
    isMagnetURI('magnet:?xt=urn:btih:C510E15DB53588BDB089EF28F813FB21DFF4E93D')      // true
    

    Parameters

    • str: string

    Returns boolean

Const isMobile

  • isMobile(str: string): boolean
  • 验证手机号,根据工信部 2019 年最新公布的手机号段

    example
    isMobile('13000000000')  // true
    

    Parameters

    • str: string

    Returns boolean

Const isMoney

  • isMoney(str: string): boolean
  • 验证金额,规则为整数或两位小数。

    example
    isMoney('12.34')     // true
    isMoney('1.5')       // true
    isMoney('1.583')     // false
    isMoney('aaa')       // false
    

    Parameters

    • str: string

    Returns boolean

Const isNewEnergyCarNumber

  • isNewEnergyCarNumber(str: string): boolean
  • 验证新能源车车牌号。

    example
    isNewEnergyCarNumber('浙AD12345')    // true
    

    Parameters

    • str: string

    Returns boolean

Const isNonNewEnergyCarNumber

  • isNonNewEnergyCarNumber(str: string): boolean
  • 验证非新能源车车牌号。

    example
    isNonNewEnergyCarNumber('京L50137')    // true
    

    Parameters

    • str: string

    Returns boolean

Const isNumberString

  • isNumberString(str: string): boolean
  • 验证数字字符串,不包含前导零。

    example
    isNumberString('0')     // true
    isNumberString('15')    // true
    isNumberString('-3')    // true
    isNumberString('0.5')   // true
    isNumberString('01')    // false
    

    Parameters

    • str: string

    Returns boolean

Const isPassportNumber

  • isPassportNumber(str: string): boolean
  • 验证护照号码。

    example
    isPassportNumber('EF1260892')    // true
    

    Parameters

    • str: string

    Returns boolean

Const isPath

  • isPath(str: string): boolean
  • 验证路径,包含 Linux 和 Windows 的文件地址和文件夹地址。

    example
    isPath('D:\\')                // true
    isPath('D:\\1.md')            // true
    isPath('/home/')             // true
    isPath('/home/index.html')   // true
    

    Parameters

    • str: string

    Returns boolean

Const isPhone

  • isPhone(str: string): boolean
  • 验证电话号码,规则为可选的区号(3 或 4 位)加横杠,后跟 7 或 8 位数字

    example
    isPhone('010-12345678')  // true
    

    Parameters

    • str: string

    Returns boolean

Const isPostal

  • isPostal(str: string): boolean
  • 验证邮政编码。

    example
    isPostal('100065')       // true
    isPostal('180123')       // false
    

    Parameters

    • str: string

    Returns boolean

Const isQQ

  • isQQ(str: string): boolean
  • 验证 QQ 号,规则为 5 ~ 10 位的整数,其中第一位不能为零。

    example
    isQQ('10000')        // true
    isQQ('123456')       // true
    isQQ('100')          // false
    isQQ('aaa')          // false
    

    Parameters

    • str: string

    Returns boolean

Const isThunderURI

  • isThunderURI(str: string): boolean
  • 验证迅雷地址。

    example
    isThunderURI('thunder://qufodhrwoi8vymouzhjpdmvyy2hpbmeuy29tl3nvd=')  // true
    

    Parameters

    • str: string

    Returns boolean

Const isTrainNumber

  • isTrainNumber(str: string): boolean
  • 验证火车车次,规则为 GCDZTSPKXLY 或非零数字开头,后面跟 1 ~ 4 位数字。

    example
    isTrainNumber('Z201')        // true
    isTrainNumber('G401')        // true
    isTrainNumber('2063')        // true
    isTrainNumber('string')      // false
    

    Parameters

    • str: string

    Returns boolean

Const isURL

  • isURL(str: string): boolean
  • 验证 URL 地址

    example
    isURL('https://www.qq.com')   // true
    

    Parameters

    • str: string

    Returns boolean

Const isUsername

  • isUsername(str: string): boolean
  • 验证用户名,规则为大写字母、小写字母和数字,4 ~ 16 位。

    example
    isUsername('1995gs123')      // true
    

    Parameters

    • str: string

    Returns boolean

Const isVersionCode

  • isVersionCode(str: string): boolean
  • 验证语义化版本号,规则为三个以点号为分隔的数字,后面跟可选的横杠与 alpha / beta / rc 三个单词,再跟可选的点号和数字。

    example
    isVersionCode('0.0.1')           // true
    isVersionCode('0.1.0-alpha')     // true
    isVersionCode('0.2.1-beta.5')    // true
    isVersionCode('1.0.0-rc')        // true
    

    Parameters

    • str: string

    Returns boolean

Const isVideoURL

  • isVideoURL(str: string): boolean
  • 验证视频地址。

    example
    isVideoURL('http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4')                      // true
    isVideoURL('http://mirror.aarnet.edu.au/pub/TED-talks/911Mothers_2010W-480p.mp4')    // true
    

    Parameters

    • str: string

    Returns boolean

Const isWeixinCode

  • isWeixinCode(str: string): boolean
  • 验证微信号,规则为长度 6 ~ 20 位,以字母开头,后面可以跟字母,数字,横杠,下划线。

    example
    isWeixinCode('wk_21_show-me')        // true
    

    Parameters

    • str: string

    Returns boolean

Const isWindowsFileAddress

  • isWindowsFileAddress(str: string): boolean
  • 验证 Windows 文件地址。

    example
    isWindowsFileAddress('C:\\Users\\app\\code\\index.html')      // true
    

    Parameters

    • str: string

    Returns boolean

Const isWindowsFolderAddress

  • isWindowsFolderAddress(str: string): boolean
  • 验证 Windows 文件夹地址。

    example
    isWindowsFolderAddress('D:\\')      // true
    

    Parameters

    • str: string

    Returns boolean

Const isWindowsPath

  • isWindowsPath(str: string): boolean
  • 验证 Windows 路径,包含文件地址和文件夹地址。

    example
    isWindowsPath('D:\\')         // true
    isWindowsPath('D:\\1.md')     // true
    

    Parameters

    • str: string

    Returns boolean

数字相关方法 Functions

Const limit

  • limit(target: number, min: number, max: number): number
  • 确保数值在最值闭区间之内,如果超出限界,则置换为离它最近的最大值或最小值

    example
    limit(5, 3, 9)   // 5
    limit(3, 5, 9)   // 5
    limit(13, 5, 9)  // 9
    

    Parameters

    • target: number

      要检查的值

    • min: number

      最小值范围

    • max: number

      最大值范围

    Returns number

Const nearer

  • nearer(target: number, min: number, max: number): number
  • 求出距离指定数值最近的那个数

    example
    nearer(5, 3, 9)      // 3
    nearer(3, 5, 9)      // 5
    nearer(13, 5, 9)     // 9
    

    Parameters

    • target: number

      要检查的值

    • min: number

      最小值范围

    • max: number

      最大值范围

    Returns number

对象相关方法 Functions

Const camelCaseObject

  • camelCaseObject<T>(objOrArr: T): T
  • 将对象中的所有键小驼峰化,支持循环引用检查,用于前后端交互(以及后端与数据库交互)时的数据格式转换,支持对象数组。

    example
    camelCaseObject({ 'a-b': { c_d: 1 } })       // { aB: { cD: 1 } }
    camelCaseObject([{ a_b: 1 }, { c_d: 2 }])    // [{ aB: 1 }, { cD: 2 }]
    

    Type parameters

    • T: object | object[]

    Parameters

    • objOrArr: T

      被转换的对象或对象数组

    Returns T

Const pascalCaseObject

  • pascalCaseObject<T>(objOrArr: T): T
  • 将对象中的所有键大驼峰(Pascal Case)化,支持循环引用检查,用于前后端交互(以及后端与数据库交互)时的数据格式转换,支持对象数组。

    example
    pascalCaseObject({ 'a-b': { c_d: 1 } })       // { AB: { CD: 1 } }
    pascalCaseObject([{ a_b: 1 }, { c_d: 2 }])    // [{ AB: 1 }, { CD: 2 }]
    

    Type parameters

    • T: object | object[]

    Parameters

    • objOrArr: T

      被转换的对象或对象数组

    Returns T

Const removeEmptyValue

  • removeEmptyValue(data: object, emptyValue?: (undefined | null | string)[]): object
  • 将对象中的所有空值(默认为 null, undefined, '')移除,支持任意嵌套层级和深比较。

    不支持循环比较(如 { a: { b: '' }, c: 1 } 在将 {}'' 设为空值时只会移除 b,此时 a{} 但不会再次检查)。

    此方法不会修改原对象。

    example
    removeEmptyValue({ a: 1, b: '', c: null, d: undefined, e: { f: '' } })   // { a: 1, e: {} }
    removeEmptyValue({ a: { b: {} }, c: 1, d: {} }, [{}])                    // { a: { }, c: 1 }
    

    Parameters

    • data: object

      被处理的对象

    • emptyValue: (undefined | null | string)[] = ...

      被认为是「空值」的列表,默认为 [null, undefined, '']

    Returns object

Const replaceValueFromObject

  • replaceValueFromObject(obj: any, from: any, to: any, autoExecuteFunction?: boolean): any
  • 将对象 / 数组中的某个值(或满足某个条件的值,使用 SameValueZero 算法)替换成另一个值(或将原值处理后的值),支持任意嵌套层级和复杂类型深比较。

    该方法不会修改原对象 / 数组。

    replaceValueFromObject({ x: 1 }, 1, 2)                               // { x: 2 }
    replaceValueFromObject({ x: 1 }, { x: 1 }, 2)                        // 2
    replaceValueFromObject({ x: { y: 1 } }, { y: 1 }, 2)                 // { x: 2 }
    replaceValueFromObject({ x: { y: 1 } }, 1, 2)                        // { x: { y: 2 } }
    replaceValueFromObject([1, 2, 3, 1], 1, '3')                         // ['3', 2, 3, '3']
    replaceValueFromObject([NaN, NaN, 2, 3], NaN, '3')                   // ['3', '3', 2, 3]
    replaceValueFromObject([1, 2, 3, 1], v => v % 2 === 0, '3')          // [1, '3', 3, 1]
    replaceValueFromObject([1, 2, 3, 1], v => v % 2 === 0, y => y + 10)  // [1, 12, 3, 1]
    

    Parameters

    • obj: any

      被转换的数组 / 对象

    • from: any

      某个值,或满足值的条件函数,此时接收 obj 中的部分值

    • to: any

      另一个值,或处理值的函数,此时接收 obj 中的部分值

    • autoExecuteFunction: boolean = true

      fromto 是函数时,是否作为转换条件执行,默认为 true,对于替换函数的特殊场景时需要置为 false

    Returns any

Const snakeCaseObject

  • snakeCaseObject<T>(objOrArr: T): T
  • 将对象中的所有键下划线化,支持循环引用检查,用于前后端交互(以及后端与数据库交互)时的数据格式转换,支持对象数组。

    example
    snakeCaseObject({ aB: { cD: 1 } })           // { a_b: { c_d: 1 } }
    snakeCaseObject([{ aB: 1 }, { cD: 2 }])      // [{ a_b: 1 }, { c_d: 2 }]
    

    Type parameters

    • T: object | object[]

    Parameters

    • objOrArr: T

      被转换的对象或对象数组

    Returns T

统计相关方法 Functions

Const distance

  • distance(arr: number[]): number
  • 极差,为了与范围(range)区别,函数名设置为 distance

    example
    distance([1, 2, 3, 4, 5])    // 4
    distance([])                 // NaN
    

    Parameters

    • arr: number[]

      被统计的数据

    Returns number

Const standardDeviation

  • standardDeviation(arr: number[]): number
  • 标准差

    example
    standardDeviation([1, 1, 3, 3])  // 1
    

    Parameters

    • arr: number[]

      被统计的数据

    Returns number

Const variance

  • variance(arr: number[]): number
  • 方差

    example
    variance([1, 2, 3, 4, 5])    // 2
    variance([])                 // NaN
    

    Parameters

    • arr: number[]

      被统计的数据

    Returns number

字符串相关方法 Functions

Const byteLen

  • byteLen(str: string, charset?: "utf-8" | "utf-16"): number
  • 计算字符串所占的内存字节数,默认使用 UTF-8 的编码方式计算,也可指定为 UTF-16。

    example
    byteLen('1')                 // 1
    byteLen('1', 'utf-16')       // 2
    byteLen('\u{5f8}')           // 2
    byteLen('\u{5f8}', 'utf-16') // 2
    byteLen('以')                // 3
    byteLen('以', 'utf-16')      // 2
    byteLen('𪚥')                // 4
    byteLen('𪚥', 'utf-16')      // 4
    

    Parameters

    • str: string

      要计算的字符串

    • charset: "utf-8" | "utf-16" = 'utf-8'

      编码格式,支持 utf8 和 utf16,默认为 utf8

    Returns number

    字节数

Const escapeSqlTemplate

  • escapeSqlTemplate(strings: string, ...values: any[]): string
  • 转义 SQL 字符串,在模板字符串前面使用。

    具体转换规则为:

    • 如果是布尔类型的值,true 转换成 'true'false 转换成 'false'
    • 如果是数字类型的值,转换成对应的字符串。
    • 如果是日期类型的值,转换成 YYYY-MM-DD HH:mm:ss 对应的字符串。
    • 如果是字符串,会对引号、换行符、制表符等特殊字符进行转义。
    • 其他类型则会报错。
    example
    escapeSqlTemplate`SELECT * FROM table WHERE name = ${'a'}`   // 'SELECT * FROM table WHERE name = \'a\''
    escapeSqlTemplate`${JSON.stringify({a: 1})}`                 // '\'{\\\"a\\\":1}\''
    

    Parameters

    • strings: string
    • Rest ...values: any[]

    Returns string

Const pascalCase

  • pascalCase(str: string): string
  • 将字符串转换成大驼峰格式(Pascal Case)。

    params

    str 被转换的字符串

    example
    pascalCase('hello-world')        // 'HelloWorld'
    pascalCase('helloWorld')         // 'HelloWorld'
    pascalCase('hello_world')        // 'HelloWorld'
    pascalCase('hello world')        // 'HelloWorld'
    pascalCase('helloWorld world')   // 'HelloWorldWorld'
    pascalCase('--hello-world--')    // 'HelloWorld'
    pascalCase('__hello_world__')    // 'HelloWorld'
    pascalCase('__HELLO_WORLD__')    // 'HelloWorld'
    

    Parameters

    • str: string

    Returns string

Const truncate

  • truncate(target: string, length?: number, truncation?: string): string
  • 用于对字符串进行截断处理。当超过限定长度(默认是 30),默认添加 3 个点号。

    example
    truncate('hello world', 5)                       // 'he...'
    truncate('hello world', 300)                     // 'hello world'
    truncate('hello world', 8, '--__')               // 'hell--__'
    truncate('hello world hello world hello world')  // 'hello world hello world hel...'
    

    Parameters

    • target: string

      目标字符串

    • length: number = 30

      限定长度

    • truncation: string = '...'

      省略符

    Returns string

Legend

Generated using TypeDoc