Skip to main content

JS一行代码小工具

生成一个随机字符串

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

randomString() // gi1qtdego0b
randomString() // f3qixv40mot
randomString() // eeelv1pm3ja

消除特殊的HTML字符,防止XSS攻击

const escape = (str) => str.replace(/[&<>"']/g, (m) => (
{ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m]
));

// 测试
escape('<div class="medium">Hi Medium.</div>');
// 返回 &lt;div class=&quot;medium&quot;&gt;Hi Medium.&lt;/div&gt

字符串中的每一个单词首字母大写

const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase());

uppercaseWords('hello world'); // 'Hello World'

// 更简单的方式: const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase()); 😀

字符串转换为小驼峰🐫

const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));

toCamelCase('background-color'); // backgroundColor
toCamelCase('-webkit-scrollbar-thumb'); // WebkitScrollbarThumb
toCamelCase('_hello_world'); // HelloWorld
toCamelCase('hello_world'); // helloWorld

数组去重

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((item) => (Array.isArray(item) ? flat(item) : item)));
// Or
const flat = (arr) => arr.reduce((pre, next) => (Array.isArray(next) ? [...pre, ...flat(next)] : [...pre, next]), []);

flat(['cat', ['lion', 'tiger']]) // ['cat', 'lion', 'tiger']

移除数组中所有的falsy的值 (Remove falsy values from array )

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

实现 Math.pow()

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)

round(1.005, 2) //1.01
round(1.555, 2) //1.56

生成一个随机的hex color

const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`

randomColor() // #9dae4f
randomColor() // #6ef10e

RGB color 转 hex

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

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

检测是否处于dark mode

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

获取某一天是当年的第几天

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

dayOfYear(new Date())

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

const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));

diffDays(new Date("2023-03-17"), new Date("2023-12-25")) // 283