/** * @file 字符串相关的 utils */ export { default as camelCase } from 'lodash/camelCase' export { default as capitalize } from 'lodash/capitalize' export { default as endsWith } from 'lodash/endsWith' export { default as isString } from 'lodash/isString' export { default as kebabCase } from 'lodash/kebabCase' export { default as snakeCase } from 'lodash/snakeCase' export { default as toLower } from 'lodash/toLower' export { default as trim } from 'lodash/trim' export { default as trimStart } from 'lodash/trimStart' export { default as trimEnd } from 'lodash/trimEnd' export { default as truncate } from 'lodash/truncate' export { default as upperFirst } from 'lodash/upperFirst' export { default as lowerCase } from 'lodash/lowerCase' export { default as split } from 'lodash/split' /** * 生成一个 4 位由字母和数字组成的随机验证码 * * @returns generated pin code * @example * ```javascript * const code = getRandomPINCode() // => '2mz8' * ``` */ export const getRandomPINCode = () => Math.random().toString(36).substr(2, 4) /** * 生成一个 12 位左右, 可作为 uuid 的随机字符串 * * @returns generated uuid * @example * ```javascript * const id = getRandomId() // => 'kk3dqh6t99589' * ``` */ export const getRandomId = () => Date.now().toString(36) + Math.random().toString(36).substr(2, 5) /** * 安全解析 JSON String * * @param str - JSON String * @returns 解析后的 JSON Object,解析失败返回 null */ export function safeParseJSON(str?: string): any { if (!str) return null try { return JSON.parse(str) } catch (e) { console.error(e) return null } } /** * 将 string 转化为可被 regexp 正常识别的状态 * 比如 '\w+' 会转化为 '\\w+',这样 new Regexp() 时才能被正常转化 * * @param str - string * @returns - 转化后的 string */ export function escapeStringRegExp(str: string) { return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') } /** * 从字符串中解析出 url * 与链接输入框逻辑一致,开头需要有协议 http(s) * 支持链接包含中文 * * @param str - string * @returns matched[] - string[] */ export const matchUrlStr = (str: string) => { const reg = /(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|%|&|[\u4e00-\u9fa5]|-)+)/g return str.match(reg) || [] }