1. 颜色RGB转十六进制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(0, 51, 255);
// Result: #0033ff
2. 生成随机十六进制颜色
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex());
// Result: #92b008
3. 获取用户选中的文本
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
4. 复制到剪切板
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
5. 获取浏览器Cookie的值
const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
cookie('_cbh');
6. 清楚全部Cookie
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
7. 从url获取查询参数
可以通过传递 window.location 或原始 URL goole.com?search=easy&page=3 轻松地从 url 检索查询参数
const getParameters = (URL) => {
URL = JSON.parse(
'{"' +
decodeURI(URL.split("?")[1])
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"') +
'"}'
);
return JSON.stringify(URL);
};
getParameters(window.location);
// Result: { search : "easy", page : 3 }
或者更为简单的:
Object.fromEntries(new URLSearchParams(window.location.search))
// Result: { search : "easy", page : 3 }
微信小程序获取url参数
const getUrlParam = (url, name) => {
// 正则筛选地址栏
var reg = new RegExp("(^|[?|&])" + name + "=([^&]*)(&|$)");
// 匹配目标参数
var result = url.match(reg);
//返回参数值
return result ? decodeURIComponent(result[2]) : null;
}
8. 求平均值
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
9. 翻转字符串
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// Result: 'dlrow olleh'
10. 生成guid
const generateUUID = () => {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,(c) => {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
};
11. 页面传递参数过长
可以不转json,转json是进行数据深拷贝
//传递
encodeURIComponent(JSON.stringify(row))
//接收
JSON.parse(decodeURIComponent(options.row))
12. 金额保留指定小数位,并转化为千分位
const formatNumber = (num, n = 2) => {
return num.toFixed(n).replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
return $1 + ',';
});
}
13. 去除空格
去除字符串内所有的空格:str = str.replace(/\s*/g,"");
去除字符串内两头的空格:str = str.replace(/^\s*|\s*$/g,"");
去除字符串内左侧的空格:str = str.replace(/^\s*/,"");
去除字符串内右侧的空格:str = str.replace(/(\s*$)/g,"");
14. 获取参数的数据类型
function getType(a){
var obj = Object.prototype.toString.call(a); //区分对象类型 确定当前的数据的类型
var sub = obj.substr(8);
// stringObject.substr(start,length) start 要抽取的子符串的起始下标,
// length 截取的长度,如果不写则表示从start开始截取到最后 ,stringObject表示某一字符串
var len = sub.length;
var sub = sub.substr(0,len-1)
var rs = sub.toLowerCase(sub) //转换成小写
return rs ;
}
console.log(getType("a")); //string
未完待续…