为了账号安全,请及时绑定邮箱和手机立即绑定

一些很实用util工具函数

标签:
JavaScript

  1、生成UUID。

  尽管前端已有Symbol,但这更多是在于确保对象的属性唯一,不过有时候也会用到关于生成ID的场景。

const createUUID = () => new Date().getTime().toString(32) + Math.floor(Math.random() * 999999).toString(32);

  2、手动实现一个jsonp。

在当下的情况中,解决跨域问题越来越趋向于代理,实际上jsonp也是另一种解决办法,仅仅将XHR请求变成非XHR请求(即script)。

class dorseyJsonp {

    constructor (url, callback) {

        let id = this.createRandomId();

        window[id] = function (result) {

            if(callback){
                callback(result);
            }

            let scriptID = document.querySelector('#' + id);
            scriptID.parentNode.removeChild(scriptID);
            window[scriptID] = null;
        }
        let script = document.createElement('script');

        script.src = url;
        script.id = id;
        script.type = 'text/javascript';

        document.body.appendChild(script);
    }
    createRandomId () {

        return 'query' + Math.floor(Math.random() * 10000).toString(32) + new Date().getTime().toString(32);
    }
}

  3、将URL的参数转化成一个对象。

如:

如输入:http://www.baidu.com/item.html#hello?pageNo=1&pageSize=30&keyword=hello
输出:{
    pageNo: '1',
    pageSize: '30',
    keyword: 'hello'
}

看看工具函数:

const getUrlParams = url => {

    let arr = url.match(/(?<=[\?&]).*?(?=(&|$))/g),
        res = {};

    arr && arr.length && arr.map(item => res[item.split('=')[0]] = item.split('=')[1]);

    return res;
}

console.log(getUrlParams('http://www.baidu.com/item.html#hello?pageNo=1&pageSize=30&keyword=hello'));
console.log(getUrlParams('http://www.baidu.com'));

  4、日期格式化。

在实际应用的过程中,可能最常见的日期格式就是’2019-11-30 09:00:00’这样的格式了,但JavaScript中似乎没有,所以需要我们自己实现。

const fill = num => num >= 10 ? num : ('0' + num);

const format = (date, formatStr) => {

	return formatStr.replace('yyyy', date.getFullYear())
	.replace('MM', fill(date.getMonth() + 1))
	.replace('dd', fill(date.getDate()))
	.replace('HH', fill(date.getHours()))
	.replace('mm', fill(date.getMinutes()))
	.replace('ss', fill(date.getSeconds()));
}

console.log(format(new Date(), 'yyyy年MM月dd日 HH时mm分ss秒'));

return format(new Date(), 'yyyy-MM-dd HH:mm:ss');

  5、图片前缀替换

实际应用中,无论是网站,app也好,大型复杂系统也罢,图片资源一般都储存在专门优化过的ftp服务器,而数据库中存储的实际上仅仅是一串URL,在业务的变迁过程中,有时候会涉及到资源迁移,这样一般情况下,数据库的图片不会储存IP跟端口或域名,有些设计之初存储了,则需要我们自行替换。

const changeIPAndPort = pic => pic.replace(/https:\/\/.*:\d+\//g, 'https:172.22.20.25:8080')
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
1.3万
获赞与收藏
1519

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消