跳到主要内容

JavaScript工具函数

复制文本到剪贴板

const copyText = async (text: string) => {
await navigator.clipboard.writeText(text)
}

copyText("Hello, World!")

获取某个日期位于当年的第几天

const getDayOfYear = (date: Date) => {
const start = new Date(date.getFullYear(), 0, 0)
const diff = date - start
const oneDay = 1000 * 60 * 60 * 24
return Math.floor(diff / oneDay)
}

getDayOfYear(new Date(2022, 10, 27)) // 331

将RGB颜色灰度化(基于光感加权平均)

const rgbToGray = (r: number, g: number, b: number) => {
return 0.2126 * r + 0.7152 * g + 0.0722 * b
}

rgbToGray(50, 100, 150) // 92.98

解析url查询参数

const parseQuery = (url: string): Record<string, string> => {
const search = new URL(url).search
return Object.fromEntries(new URLSearchParams(search))
}

parseQuery("https://example.com/?a=1&b=2") // { a: "1", b: "2" }

筛选对象属性

const pick = (obj, ...keys) => {
return Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key)))
}

pick({ a: 1, b: 2, c: 3 }, "a", "c") // { a: 1, c: 3 }

随机HEX颜色

const randomHexColor = () => {
return `#${Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, "0")}`
}

randomHexColor() // "#f0a3c2"

产生随机字符串

const randomString = (length) => {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
return Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)]).join("")
}

randomString(8) // "xT3nZ8v2"

去掉字符串中的HTML标签

const stripHTML = (html) => new DOMParser().parseFromString(html, "text/html").body.textContent || ""

stripHTML("<p>Hello, <b>World</b>!</p>") // "Hello, World!"