工具函数
获取 URL 参数
javascript
const getParams = (url) => {
try {
const params = {}
const urlObj = new URL(url)
const searchParams = urlObj.searchParams.entries()
for (let [key, value] of searchParams) {
params[key] = value
}
return params
} catch (error) {
return error.message
}
}获取 n 天前的日期
javascript
const getPriorDate = (date, priorDay) => {
return new Date().setDate(date.getDate() - priorDay)
}获取 html 的字体大小
typescript
getHtmlFontSize(): number {
let htmlFontSize = getComputedStyle(window.document.documentElement)['font-size']
//以上方法返回的font-size会带单位px,如果不想要px可以做一下处理
return +htmlFontSize.slice(0, htmlFontSize.indexOf('px'))
}判断是否是奇数
js
function isOdd(num) {
if (typeof num !== 'number') {
throw new TypeError(`${num} is not a number`)
}
return num % 2 === 1 || num % 2 === -1
}数字转中文
js
/**
* 数字转中文
* @param {Number} num 万亿以下的正整数
*/
function toChineseNumber(num) {
const strs = num
.toString()
.replace(/(?=(\d{4})+$)/g, ',')
.split(',')
.filter(Boolean)
const chars = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
const units = ['', '十', '百', '千']
const bigUnits = ['', '万', '亿']
function _transform(numStr) {
let result = ''
for (let i = 0; i < numStr.length; i++) {
const digit = +numStr[i]
const c = chars[digit]
const u = units[numStr.length - 1 - i]
if (digit === 0) {
if (result[result.length - 1] !== chars[0]) {
result += c
}
} else {
result += c + u
}
}
if (result[result.length - 1] === chars[0]) {
result = result.slice(0, -1)
}
return result
}
let result = ''
for (let i = 0; i < strs.length; i++) {
const part = strs[i]
const c = _transform(part)
const u = c ? bigUnits[strs.length - 1 - i] : ''
result += c + u
}
return result
}
function toChineseBigNumber(num) {
const str = toChineseNumber(num)
const map = {
零: '零',
一: '壹',
二: '贰',
三: '叁',
四: '肆',
五: '伍',
六: '陆',
七: '柒',
八: '捌',
九: '玖',
十: '拾',
百: '佰',
千: '仟',
万: '万',
亿: '亿'
}
return str
.split('')
.map((s) => map[s])
.join('')
}一行代码实现星级评分
javascript
const getRate = (rate = 0) => '★★★★★☆☆☆☆☆'.slice(5 - rate, 10 - rate)
getRate(3)字符串的异步替换封装
js
String_prototype.asyncReplaceAll = async function (pattern, asyncFn) {
if (typeof asyncFn === 'string') {
return this.replaceAll(pattern, asyncFn)
}
if (typeof asyncFn !== 'function') {
throw new TypeError('The second argument should be an async function or a string')
}
let reg
if (typeof pattern === 'string') {
reg = new RegExp(pattern.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'), 'g')
} else if (pattern instanceof RegExp) {
if (!pattern.global) {
throw new TypeError('The pattern RegExp should have the global flag set')
}
reg = new RegExp(pattern)
} else {
throw new TypeError('The pattern should be a string or a RegExp')
}
// async 是一个函数, pattern 是一个正则表达式
const result = []
let match
let lastIndex = 0 // 上一次匹配的结束位置
while ((match = reg.exec(this)) !== null) {
const item = asyncFn(match[0])
const prefix = this.slice(lastIndex, match.index)
lastIndex = match.index + match[0].length
result.push(prefix)
result.push(item)
}
result.push(this.slice(lastIndex))
result = await Promise.all(result)
return result.join('')
}码点和码元
js
String.prototype.pointLength = function () {
let len = 0
for (let i = 0; i < this.length; ) {
len++
const point = this.charCodeAt(i)
i += point > 0xffff ? 2 : 1
}
return len
}
String.prototype.pointAt = function (index) {
let curIndex = 0 // 目前遍历到第几个码点
for (let i = 0; i < this.length; ) {
if (curIndex === index) {
const point = this.codePointAt(i)
return String.fromCodePoint(point)
}
curIndex++
const point = this.charCodeAt(i)
i += point > 0xffff ? 2 : 1
}
}
String.prototype.pointSlice(start, (end = this.pointLength())){
let result = ''
const len = this.pointLength()
for (let i = start; i < len && i < end; i++) {
result += this.pointAt(i)
}
return result
}判断是否是稀疏数组
js
/**
* 判断是否是稀疏数组
* @param {Array} arr
*/
function isSparseArray(arr) {
/**
* 1. 判断是否是数组
* 2. 判断数组长度是否等于过滤后的数组长度
*/
if (!Array.isArray(arr)) {
return false
}
for (let i = 0; i < arr.length; i++) {
if (!(i in arr)) {
// arr.hasOwnProperty(i)
return true
}
}
return false
}获取当前日期所在周的周一
js
/**
* 1.初始化日期:我们首先创建一个名为 getMonday 的函数,该函数接受一个日期参数 date。在函数内部,我们使用 new Date(date) 创建一个新的日期实例 currentDate。
* 2.获取当前星期几:接着,使用 getDay 方法获取当前日期是星期几。getDay 返回一个0到6之间的整数,0表示星期天,1表示星期一,以此推。
* 3.计算周一日期:通过计算当前日期与周一的差值,我们可以确定本周一的日期。如果当天是星期天(即 dayOfWeek === 0),则需要减去6天;否则,减去对应的天数并加1。
* 4.设置周一日期:使用 setDate 方法,将当前日期设置为本周的周一。
* 5.返回结果:函数最终返回计算出的本周一日期。
*/
const getMonday = (date) => {
const currentDate = new Date(date)
const dayOfWeek = currentDate.getDay()
const difference = currentDate.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1)
currentDate.setDate(difference)
return currentDate
}千分位格式化数字
javascript
let num = 12345678
let str = num.toString()
let newStr = str.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
str.replace(/(?=\B(\d{3})+$)/g, ',')