©️ OverlookArt
首页 / H5Webs / Javascript 常用脚本

Javascript 常用脚本

格式化时间[Date]

 1Date.prototype.Format = function (fmt) { //author: meizz
 2    var o = {
 3        "M+": this.getMonth() + 1, //月份
 4        "d+": this.getDate(), //日
 5        "h+": this.getHours(), //小时
 6        "m+": this.getMinutes(), //分
 7        "s+": this.getSeconds(), //秒
 8        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
 9        "S": this.getMilliseconds() //毫秒
10    };
11    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
12    for (var k in o)
13    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
14    return fmt;
15};
16const dateFormat = new Date().Format("yyyy-MM-dd hh:mm:ss");

深拷贝对象(Object)

1var val = JSON.parse(JSON.stringify(object));

Array 数组

移除某个元素

1Array.prototype.remove = function(val) { 
2    var index = this.indexOf(val); 
3    if (index > -1) { 
4        this.splice(index, 1); 
5    } 
6};

Array 假值去除

1const removeFalsy = (arr) => arr.filter(Boolean);
2
3removeFalsy([0, 'a', '', 'as', 'NaN', true, undefined, false]);
4
5//['a', 'as', true]

Array 去重

1var newArr = [...new Set(array)]

Array 插入数据

1// splice(start: number, deleteCount: number, ...items: T[])
2var arr = [];
3// 在头部插入一个或多个数据; start:要插入数据的位置
4arr.splice(0,0,object);
5// 或者使用 unshift 方法在头部插入一个或多个数据 
6arr.unshift(object);

生成随机

1// 随机数字
2const random = (min, max) => Math.floor(Math.random() * (max-min+1)+min);
3
4// 随机字符串
5const randomString = () => Math.random().toString(36).slice(2);
6
7// 随机色
8const randomColor = () => `#${Math.random().toString(16).slice(2,8).padEnd(6,'0')}`

转义 HTML 特殊字符

1const escape = (str) => str.replace(/[&<>"']/g, (m) => ({'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;'}[m]));
2
3escape('<div class="medium">');
4
5//&lt;div class=&quot;medium&quot;&gt;

检测暗黑模式

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

清除所有的cookie

1const clearCookies = () => {
2    document.cookie.split(';').forEach( c => {
3        document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)
4    })
5}

将字符串转为小驼峰

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

大小写转换

 1/**
 2 * str: 待转换的字符串
 3 * type: 1全大写,2全小写,3首字母大写
 4 */
 5const turnCase = (str, type) => {
 6    switch (type) {
 7        case 1:
 8            return str.toUpperCase();
 9        case 2:
10            return str.toLowerCase();
11        case 3:
12            return str[0].toUpperCase() + str.substring(1).toLowerCase();
13        default:
14            return str
15    }
16}

校验数据类型

1const typeOf = (obj) => {
2    return Object.prototype.toString.call(obj).slice(8,-1);
3}

防抖

1const debounce = () => {
2    let timer = null
3    return (callback, wait = 800) => {
4        timer&&clearTimeout(timer)
5        timer = setTimeout(callback, wait)
6    }
7}

手机号脱敏

1const hideMobile = (mobile) => {
2    reture mobile.replace(/^(\d{3})\d{4}(\d{4})$/,"$1****$2");
3}

开启全屏

 1const launchFullScreen = (element){
 2    if(element.requestFullscreen){
 3        element.requestFullscreen();
 4    }else if (element.mozRequestFullScreen){
 5        element.mozRequestFullScreen();
 6    }else if (element.msRequestFullscreen){
 7        element.msRequestFullscreen();
 8    }else if (element.webkitRequestFullscreen){
 9        element.webkitRequestFullscreen();
10    }
11}

关闭全屏

 1const exitFullScreen = () => {
 2    if(document.exitFullscreen){
 3        document.exitFullscreen();
 4    }else if (document.msExitFullscreen){
 5        document.msExitFullscreen();
 6    }else if (document.mozCancelFullScreen){
 7        document.mozCancelFullScreen();
 8    }else if (document.webkitExitFullscreen){
 9        document.webkitExitFullscreen();
10    }
11}

解析URL参数

1const getSearchParams = () => {
2    const searchPar = new URLSearchParams(window.location.search);
3    const paramsObj = {};
4    for (const [key, value] of searchPar.entries()){
5        paramsObj[key] = value;
6    }
7    return paramsObj;
8}

判断设备类型

 1const getOSType = () => {
 2    let u = navigator.userAgent;
 3    let app = navigator.appVersion;
 4    let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
 5    let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
 6    if (isIOS) {
 7        return 1;
 8    } else if (isAndroid) {
 9        return 2;
10    }else {
11        return 3;
12    }
13}

滚动到页面顶部

1const scrollToTop = () => {
2    const height = document.documentElement.scrollTop || document.body.scrollTop;
3    if(height > 0){
4        window.requestAnimationFrame(scrollToTop);
5        window.scrollTo(0, height - height / 8);
6    }
7}

滚动到元素的位置

1const smoothScroll = (element) => {
2    document.querySelector(element).scrollIntoView({
3        behavior: 'smooth'
4    });
5}

uuid

1const uuid = () => {
2    const temp_url = URL.createObjectURL(new Blob());
3    const uuid = temp_url.toString();
4    //释放这个URL
5    URL.revokeObjectURL(temp_url);
6    return uuid.substring(uuid.lastIndexOf('/')+1);
7}

金额格式化

 1/**
 2 * number: 要格式化的数字
 3 * decimals: 保留几位小数
 4 * dec_point: 小数点符号
 5 * thousands_sep: 千分位符号
 6 */
 7const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
 8    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
 9    const n = !isFinite(+number) ? 0 : +number;
10    const prce = !isFinite(+decimals) ? 2 : Math.abs(decimals);
11    const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep;
12    const dec = typeof dec_point === 'undefined' ? '.' : dec_point;
13    let s = '';
14    const toFixedFix = function(n, prec) {
15        const k = Math.pow(10, prec)
16        return '' + Math.ceil(n*k)/k;
17    }
18    s = (prec ? toFixedFix(n, prec) : ''+Math.round(n)).split('.');
19    const re = /(-?\d+)(\d{3})/
20    while (re.test(s[0])) {
21        s[0] = s[0].replace(re, '$1' + sep + '$2');
22    }
23    if((s[1] || '').length < prec) {
24        s[1] = s[1] || '';
25        s[1] += new Array(prec - s[1].length + 1).join('0');
26    }
27    return s.join(dec);
28}