1.手机号验证
// 手机号正则验证
const mobile = (mobileNum) => {
return mobileNum.match(/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/)
}
2.检测过滤空格
// 检测过滤空格
const filterSpace = str =>{
return str.replace(/ /g, '')
}
3.时间戳转换成日期(提供两种)
3.1 开发小程序项目时所用(此实例为小程序默认实例)
// 时间戳为10位需*1000,时间戳为13位的话不需乘1000
const formatTime = dateTime => {
const date = new Date(dateTime);
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
// 不足补零
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
3.2 开发h5时所用
/**
* 根据时间戳获取当前时间
* @module getTime
* @class 类名
* @param {number} time 时间戳
* @return {string} 2018-07-19 14:11:51
*/
getTime: function (time) {
var date = new Date(time);
var year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours(),
min = date.getMinutes(),
sec = date.getSeconds();
var newTime = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (min < 10 ? '0' + min : min) + ':' + (sec < 10 ? '0' + sec : sec);
return newTime;
},
4. 小数点后保留两位(笔者开发电商项目时,所用展示商品价格所用)
/**
* 返回小数点后保留两位数
* @module stayTwo
* @class 类名
* @param {number} val 整数或小数
* @return {string} val 保留两位数的字符串数字
*/
stayTwo: function (val) {
var val = Math.floor(parseFloat(val) * 100) / 100; // 非四舍五入
var _val = val.toString().split(".");
if (_val.length == 1) {
val = val.toString() + ".00";
return val;
}
if (_val.length > 1) {
if (_val[1].length < 2) {
val = val.toString() + "0";
}
return val;
}
}
5.判断是否为微信内置浏览器
function is_weixn() {
var ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == "micromessenger") {
return true;
} else {
return false;
}
};
if(is_weixn()){
// 基于微信浏览器
}else{
// 非微信浏览器
}
6.向字符串的指定位置插入指定内容
//a 原字符串 b 插入的位置 c 插入的内容
function(a,b,c){
return a.slice(0, b) + c + a.slice(b);
}