实用的 JavaScript 一行代码
XPoet 自由程序猿

检查日期是否有效

1
2
3
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf())

isDateValid('Thu Nov 16 2023 15:44:26 GMT+0800') // true

计算两个日期之间的间隔天数

1
2
3
const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)

dayDif(new Date("2023-11-16"), new Date("2024-1-1")) // 46

查找日期位于一年中的第几天

1
2
3
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)

dayOfYear(new Date()) // 307

字符串首字母大写

1
2
3
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("hello world") // 'Hello world'

翻转字符串

1
2
3
const reverseStr = str => str.split('').reverse().join('')

reverseStr('hello world') // 'dlrow olleh'

生成一个随机字符串

1
2
3
const randomString = () => Math.random().toString(36).slice(2)

// randomString() // 'e3ogdzoa2sh'

生成一个 UUID 字符串

1
2
const getUuid = () => Number(Math.random().toString().substr(2, 5) + Date.now()).toString(36)
// getUuid() // 5agy96in1r00

从指定位置截断字符串

1
2
3
const truncateString = (string, length) => string.length < length ? string : `${string.slice(0, length)}...`

truncateString('hello world', 3) // 'hel...'

去除字符串中的 HTML 标签

1
2
3
const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || ''

stripHtml('<div>123</div>') // '123'

去除数组中的重复项

1
2
3
const myUnique = array => [...new Set(array)]

myUnique([1, 1, 2, 3]) // [1, 2, 3]

获取一组数字的平均值

1
2
3
const average = (...args) => args.reduce((a, b) => a + b) / args.length

average(1, 2, 3, 4, 5, 6, 7, 8, 9) // 5

获取指定位数四舍五入的值

1
2
3
4
const myRound = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)

myRound(1.005, 2) // 1.01
myRound(1.555677, 3) // 1.556

RGB 转化为十六进制

1
2
3
4
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)

rgbToHex(255, 255, 255) // '#ffffff'
rgbToHex(0, 0, 0) // '#000000'

获取选中的文本

1
2
3
const getSelectedText = () => window.getSelection().toString()

getSelectedText()

检测是否是黑暗模式

1
2
3
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode)

获取变量的类型

1
2
3
4
5
6
7
8
9
10
11
12
13
const myTypeOf = (data) => Object.prototype.toString.call(data).slice(8, -1).toLowerCase()

// 测试
console.log(myTypeOf(1)) // number
console.log(myTypeOf('1')) // string
console.log(myTypeOf(true)) // boolean
console.log(myTypeOf([])) // array
console.log(myTypeOf({})) // object
console.log(myTypeOf(/^/)) // regexp
console.log(myTypeOf(new Date())) // date
console.log(myTypeOf(Math)) // math
console.log(myTypeOf(() => {})) // function
console.log(myTypeOf()) // undefined

判断对象是否为空

1
2
3
4
const isEmptyObj = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object

isEmptyObj({}) // true
isEmptyObj({xx: 123}) // false

持续完善中 …

 REWARD AUTHOR
 Comments
Comment plugin failed to load
Loading comment plugin