javascript 工作中常用单行代码汇总
交换两个变量
[foo, bar] = [bar, foo]
生成随机字符串
const randomString = () => Math.random().toString(36).slice(2)
randomString() // g21qtdego0s
转义HTML特殊字符
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
uppercaseWords('hello world'); // 'Hello World'
判断邮箱
export const isEmail = (s) => {
return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}
手机号码
export const isMobile = (s) => {
return /^1[0-9]{10}$/.test(s)
}
是否为null
export const isNull = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Null'
}
是否undefined
export const isUndefined = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Undefined'
}
是否是数组
export const isArray = (o) => {
return Object.prototype.toString.call(o).slice(8, -1) === 'Array'
}
是否是移动端
export const isDeviceMobile = () => {
return /android|webos|iphone|ipod|balckberry/i.test(ua)
}
去除html标签
export const removeHtmltag = (str) => {
return str.replace(/<[^>]+>/g, '')
}
获取url参数
export const getQueryString = (name) => {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
const search = window.location.search.split('?')[1] || '';
const r = search.match(reg) || [];
return r[2];
}
删除数组中的重复值
const removeDuplicates = (arr) => [...new Set(arr)]
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]))
// [1, 2, 3, 4, 5, 6]
展平一个数组
const flat = (arr) =>
[].concat.apply(
[],
arr.map((a) => (Array.isArray(a) ? flat(a) : a))
)
// Or
const flat = (arr) => arr.reduce((a, b) => (Array.isArray(b) ? [...a, ...flat(b)] : [...a, b]), [])
flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']
从数组中删除虚假值
const removeFalsy = (arr) => arr.filter(Boolean)
removeFalsy([0, 'a string', '', NaN, true, 5, undefined, 'another string', false])
// ['a string', true, 5, 'another string']
获取两个数之间的随机整数
const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
random(1, 50) // 25
random(1, 50) // 34
计算两个日期相差天数
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
diffDays(new Date("2022-1-3"), new Date("2022-2-1")) // 90
从日期中获取一年中的哪一天
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
dayOfYear(new Date())
清除所有cookies
const clearCookies = () => document.cookie.split(';').forEach((c) => (document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)))
生成随机颜色
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`
randomColor() // #9dae4f
randomColor() // #6ef10e
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。