文章目錄
- 一、前言
- 二、生成隨機字符串
- 三、轉義`HTML`特殊字符
- 四、單詞首字母大寫
- 五、將字符串轉換為小駝峰
- 六、刪除數組中的重復值
- 七、移除數組中的假值
- 八、獲取兩個數字之間的隨機數
- 九、將數字截斷到固定的小數點
- 十、日期
- 10.1、計算兩個日期之間天數
- 10.2、從日期中獲取是一年中的哪一天
- 十一、將`RGB`顏色轉換為十六進制顏色值
- 十二、檢測黑暗模式
- 十三、、最后

一、前言
本專題主要是分享JavaScript實用小技巧,希望能提高大家的工作效率。
二、生成隨機字符串
當我們需要一個唯一id
時,通過Math.random
創建一個隨機字符串
const randomString = () => Math.random().toString(36).slice(2)
console.log(randomString()) // ugvy2k3eiqq
console.log(randomString()) // f4s72hycpfr
console.log(randomString()) //1xg2nsbsfnb
三、轉義HTML
特殊字符
解決XSS
方法之一就是轉義HTML
。
const escape = (str) => str.replace(/[&<>"']/g, (m) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]))
console.log(escape('<div class="medium">Hi Medium.</div>'))
// <div class="medium">Hi Medium.</div>
四、單詞首字母大寫
const uppercaseWords = (str) => str.replace(/^(.)|\s+(.)/g, (c) => c.toUpperCase())
console.log(uppercaseWords('hello world')) // 'Hello World'
五、將字符串轉換為小駝峰
const toCamelCase = (str) => str.trim().replace(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''));
console.log(toCamelCase('background-color')); // backgroundColor
console.log(toCamelCase('-webkit-scrollbar-thumb')); // WebkitScrollbarThumb
console.log(toCamelCase('_hello_world')); // HelloWorld
console.log(toCamelCase('hello_world')); // helloWorld
六、刪除數組中的重復值
得益于ES6
,使用Set
數據類型來對數組去重太方便了。
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 removeFalsy = (arr) => arr.filter(Boolean)
console.log(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)
console.log(random(1, 50)) // 48
console.log(random(1, 50)) // 6
九、將數字截斷到固定的小數點
const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
console.log(round(1.005, 2)) // 1.01
console.log(round(1.555, 2)) // 1.56
十、日期
10.1、計算兩個日期之間天數
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));
console.log(diffDays(new Date("2021-11-3"), new Date("2022-2-1"))) // 90
10.2、從日期中獲取是一年中的哪一天
const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24))
console.log(dayOfYear(new Date())) // 344
十一、將RGB
顏色轉換為十六進制顏色值
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
console.log(rgbToHex(255, 255, 255)) // '#ffffff'
十二、檢測黑暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode)
十三、、最后
本人每篇文章都是一字一句碼出來,希望對大家有所幫助,多提提意見。順手來個三連擊,點贊👍收藏💖關注?,一起加油?