携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天,点击查看活动详情
在本文中,我将介绍一些有用的 JavaScript 单行代码,它们可以用于快递处理一些事情,简化代码。
获取用户在网页上选择或突出显示的文本:
const getSelectedText = () => window.getSelection().toString();
console.log(getSelectedText);
滚动
scrollTo(x,y),允许你滚动到一组特定的坐标:
const scrollToTop = () => window.scrollTo(0,0);
如果你想要一个平滑的滚动动画,只需执行以下操作:
const Top = () => window.scrollTo({top:0, behavior: 'smooth'});
获取流量
获取指定时间段内通过互联网连接传输的数据量:
navigator.connection.downlink;
重定向
将用户重定向到指定位置,可以执行以下操作:
const urlRedirect = url => location.href = url;
urlRedirect('https://xxx.xxx/');
清除所有 cookies
const clearCookies = document.cookie.split(';').forEach((cookie) => (document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`)));
反转字符串
可以使用 ·split、join 和 reverse· 方法反转字符串。
const strReverse = str => [...str].reverse().join('');
strReverse('abc'); // cba
生成随机十六进制
- 生成随机十六进制:使用
Math.random()和padEnd()生成随机十六进制代码
const hexClr = () => '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0');
console.log(hexClr());
字符串转大写
- 将一个字符串大写:Javascript 没有内置的
capitalize函数,所以我们可以使用以下代码进行处理:
let str = 'follow me for amazing posts';
let capStr = str.replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));
console.log(capStr);
剪贴板
- 复制到剪贴板:使用
navigator.clipboard.writeText轻松将任何文本复制到剪贴板。
const copy = (text) => navigator.clipboard.writeText(text);
copy('前端修罗场');
删除重复值
const uniqueValues= (arr) => [...new Set(arr)];