开发中常用的js工具函数 超级全
isMobile: function(mobile) {
if (!mobile) {
utils.toast('请输入手机号码');
return false
}
if (!mobile.match(/^1[3-9][0-9]\d{8}$/)) {
utils.toast('手机号不正确');
return false
}
return true
},
//判断字符串是否为空
isEmpty: function(str) {
if (str === '' || str === undefined || str === null) {
return true;
} else {
return false;
}
},
//日期格式化
formatDate: function(formatStr, fdate) {
if (fdate) {
if (~fdate.indexOf('.')) {
fdate = fdate.substring(0, fdate.indexOf('.'));
}
fdate = fdate.toString().replace('T', ' ').replace(/\-/g, '/');
var fTime, fStr = 'ymdhis';
if (!formatStr)
formatStr = "y-m-d h:i:s";
if (fdate)
fTime = new Date(fdate);
else
fTime = new Date();
var month = fTime.getMonth() + 1;
var day = fTime.getDate();
var hours = fTime.getHours();
var minu = fTime.getMinutes();
var second = fTime.getSeconds();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
hours = hours < 10 ? ('0' + hours) : hours;
minu = minu < 10 ? '0' + minu : minu;
second = second < 10 ? '0' + second : second;
var formatArr = [
fTime.getFullYear().toString(),
month.toString(),
day.toString(),
hours.toString(),
minu.toString(),
second.toString()
]
for (var i = 0; i < formatArr.length; i++) {
formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]);
}
return formatStr;
} else {
return "";
}
},
//金额格式化
rmoney: function(money) {
return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1,').replace(
/\,$/, '').split('').reverse().join('');
},
//格式化手机号码
formatNumber: function(num) {
return num.length === 11 ? num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : num;
},
//内容替换
replaceAll: function(text, repstr, newstr) {
return text.replace(new RegExp(repstr, "gm"), newstr);
},
//去空格
trim: function(value) {
return value.replace(/(^\s*)|(\s*$)/g, "");
},
//获取token
getToken: function() {
return uni.getStorageSync("token")
},
isIphoneX: function() {
const res = uni.getSystemInfoSync();
let iphonex = false;
let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
const model = res.model.replace(/\s/g, "").toLowerCase()
if (models.includes(model)) {
iphonex = true;
}
return iphonex;
},
isAndroid: function() {
const res = uni.getSystemInfoSync();
return res.platform.toLocaleLowerCase() == "android"
},
modal: function(title, content, showCancel = false, callback, confirmColor, confirmText, cancelColor, cancelText) {
uni.showModal({
title: title || '提示',
content: content,
showCancel: showCancel,
cancelColor: cancelColor || "#555",
confirmColor: confirmColor || "#e41f19",
confirmText: confirmText || "确定",
cancelText: cancelText || "取消",
success(res) {
if (res.confirm) {
callback && callback(true)
} else {
callback && callback(false)
}
}
})
},
toast: function(text, duration, success) {
uni.showToast({
title: text || "出错啦~",
icon: success || 'none',
duration: duration || 2000
})
},