欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

校验及数据处理

程序员文章站 2022-05-18 19:37:28
...

校验及数据处理

1、URL校验
    // 1.验证url
	function isURL(str_url) {
		var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
		+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-][email protected])?" // ftp的[email protected]
		+ "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
		+ "|" // 允许IP和DOMAIN(域名)
		+ "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
		+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
		+ "[a-z]{2,6})" // first level domain- .com or .museum
		+ "(:[0-9]{1,4})?" // 端口- :80
		+ "((/?)|" // a slash isn't required if there is no file name
		+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
		var re = new RegExp(strRegex);
		return re.test(str_url);
	}
	
	//2.url
    //例如http://www.baidu.com
    var REG_URL = /^(http?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
    
	//3.url(不带http/https)
    //例如:www.baidu.com
	var URL_REG  = /^([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;

2、端口号校验
//验证ip、ip:端口
function testServerList(str){
	//IP地址 1.1.1.1
	var REG_IPADDR = /^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/;
	var flag = true;
	var arr = str.split(',');
	for(var i=0,len=arr.length;i<len;i++){
		if(!REG_IPADDR.test(arr[i])){
			var arr1 = arr[i].split(':');
			if(!REG_IPADDR.test(arr1[0])){
				flag = false;
				break;
			}else {
				if(isNaN(arr1[1]) || arr1[1] <= 0 || arr1[1]%1 != 0 || arr1[1] > 65535){
					flag = false;
					break;    					
				}
			}
		}
	}
	return flag;	
}
3、数字
//正整数
var NUM = /^[1-9]\d*$/;
//整数
VAR REG = /^([\d]+)$/
//整数和浮点数
var reg = /^\d+(?=\.{0,1}\d+$|$)/;
4、主机名
const hostnameReg = /^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9-]*[a-zA-Z0-9]).)*([A-Za-z]|[A-Za-z][A-Za-z0-9-]*[A-Za-z0-9])$/im;
5、MAC
方法1:
//mac地址格式
var mac_fro = /^([0-9a-f]{2}:){1,4}\*$/;
var mac_end = /^[A-Fa-f0-9]{1,2}\:[A-Fa-f0-9]{1,2}\:[A-Fa-f0-9]{1,2}\:[A-Fa-f0-9]{1,2}\:[A-Fa-f0-9]{1,2}\:[A-Fa-f0-9]{1,2}$/;
方法2:
const macReg = /^(([a-f0-9]{2}:)|([a-f0-9]{2}-)){5}[a-f0-9]{2}$/im;
6、包含中文
var reg = /[\u4e00-\u9fa5]/
7、是否为日期
isDate: function (s) {
    s = sort.trim(s);
    var re = /^(([1,2]\d\d\d)-([1-9]|0\d|1[0-2])-([0-9]|[0-2]\d|3[0-1])( ([0,1]\d|2[0-3]):([0-5][0-9]):([0-5][0-9]))*$)/;
    return re.test(s);
},        
8、是否为时间
isTime: function (s) {
    s = sort.trim(s);
    var re = /^(\d\d):([0-5][0-9]):([0-5][0-9])$/;
    return re.test(s);
},     
9、计算字符数
function getStringBytes(str){
	if(typeof str !=='string'){
		return 0;
	}
	var length = 0;
	var encoder = new TextEncoder();
	for(var s of str){
		length += encoder.encode(s).length > 1 ? 2 : 1;
	}
	return length;
}
10、检测字符串是否为空
function isNull(str) {
	if (!str)
		return true;
	else {
		switch (typeof(str)) {
			case "string": return (/^\s*$/g).test(str);
			case "number":
			case "boolean":
			case "object":
			case "function":return false;
		}
	}
}
11、判对象是否为空
function isEmptyObject(e) {
    var t;
    for (t in e)
        return !1;
    return !0
}
12、检查ip范围
function compareIsEqualIp(ipBegin, ipEnd){
    var temp1;
    var temp2;
    temp1 = ipBegin.split(".");
    temp2 = ipEnd.split(".");

    if(ipBegin === ipEnd) {
    	top.$.tips("起始IP不能和结束IP一致");
    	return false;
    }

    for (var i = 0; i < 3; i++)  {
        if (parseInt(temp1[i]) != parseInt(temp2[i])){
        	top.$.tips("前三位必须一致");
            return false;
            break;
        }
    }
    return true;
}
13、深拷贝
JSON.parse(JSON.stringify(obj))
14、includes(es6)
var arr1 = [{id:2,name:"123"},{id:4,name:"456"}];
var arr2 = ["2"];
var list  = arr1.filter(item => !arr2.includes(item.id.toString()));
var arr = list.map(item => item.id);
15、检查2个数组中数否有相同的数据
Array.ExistsSameValues = function(a1, a2) {
    var exists = false;
    if(a1 instanceof Array && a2 instanceof Array){
        for (var i=0,iLen=a1.length; i<iLen; i++){
            for (var j=0,jLen=a2.length; j<jLen; j++){
                if (a1[i]===a2[j]){
                    return true;
                }
            }
        }
    }
    return exists;
};		
16、判断一个数组中是否存在重复数据
function isRepeat(arr){
    var hash = {};
    for(var i in arr) {
        if(hash[arr[i]])
            return true;
        hash[arr[i]] = true;
    }
     return false;
}
17、数组去重
 //方法一
Array.Unique = function(arr){
	var newArr = [],
		origLen = arr.length,
		found,
		x, y;
	for ( x = 0; x < origLen; x++ ) {
		found = undefined;
		for ( y = 0; y < newArr.length; y++ ) {
			if ( arr[x] === newArr[y] ) {
			  found = true;
			  break;
			}
		}
		if ( !found) newArr.push( arr[x] );
	}
	return newArr;
}
 //方法二
function removal(arr){
    var res = [];
    res = arr.filter(function(item){
        return res.filter(d => d.id == item.id)[0] ? '' :res.push(item);
    });
    return res;
}
//方法三
/**
 * 过滤JS数组中的空值,返回新的数组
 * @param array 需要过滤的数组
 * @returns {Array} []
 */
function clear_arr_trim(array) {
    for(var i = 0 ;i<array.length;i++)
    {
        if(array[i] == "" || typeof(array[i]) == "undefined")
        {
            array.splice(i,1);
            i= i-1;
        }
    }
    return array;
}		
18、filter方法
//方法一
var item = subtypelist.filter(function(item, index) {

	return item.type == type;
});
//方法二
var item = subtypelist.filter(d => d.type == type)[0].data;
//去掉空数组空字符串、undefined、null
var newArr = arr.filter(item => item);    
19、输入start和end 生成一个数组
function makeArr(start,end){
	var arr = [];
	if(end >= start){
		for (var i = start; i <= end; i++) {
			arr.push(i)
		}
	}
	return arr
}
20、将端口号中的端口段 改为 端口
function transPort(arr) {
	var newArr = [];
	if (arr instanceof Array) {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].indexOf('-') != -1) {
				var arrs = makeArr(arr[i].split('-')[0], arr[i].split('-')[1]);
				arr.push(arrs);
				arr[i] = '';
			}
		}
	}
	// 生成干净的数组
	var reg = /[\d\.]+\,([\d\.]+)/g;
	newArr = arr.join(",").split(",");
	// 去重
	newArr = Array.Unique(newArr);
	newArr = newArr.sort();

	// 去掉第一个空数据
	if (newArr[0] == "") {
		newArr.shift()
	}
	return newArr
}
21、IP地址比较大小
function compareIP(ipBegin, ipEnd){
    var temp1;
    var temp2;
    temp1 = ipBegin.split(".");
    temp2 = ipEnd.split(".");
    for (var i = 0; i < 4; i++)  {
        if (parseInt(temp1[i])>parseInt(temp2[i])){
            return 1;
        }else if (parseInt(temp1[i])<parseInt(temp2[i])){
            return -1;
        }
    }
    return 0;
}	
22、去空格
//左去空格
ltrim: function (s) {
    return s.replace(/^\s*/, "");
},
//右去空格
rtrim: function (s) {
    return s.replace(/\s*$/, "");
},
//两边去空格
trim: function (s) {
    return sort.rtrim(sort.ltrim(s));
}
23、日期转时间戳
function get_unix_time(dateStr) {
    if(!dateStr) {
        return '';
    }
    var newstr = dateStr.replace(/-/g, '/');
    var date = new Date(newstr);
    var time_str = date.getTime().toString();
    return time_str.substr(0, 10);
}
24、时间戳转日期
function formatDate(tm) {
    if(tm == 0 || tm == '0' || !tm || tm == '')
    {
        return '';
    }
    var now = new Date(parseInt(tm) * 1000),
        year = now.getFullYear(),
        month = now.getMonth() + 1,
        date = now.getDate(),
        hour = now.getHours(),
        minute = now.getMinutes(),
        second = now.getSeconds();
    month = month < 10 ? '0' + (month) : month;
    date = date < 10 ? '0' + (date) : date;
    hour = hour < 10 ? '0' + (hour) : hour;
    minute = minute < 10 ? '0' + (minute) : minute;
    second = second < 10 ? '0' + (second) : second;
    return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}
25、时间戳转当日零点起的日期
function formatDateCur(timestamp) {
    var now = parseInt(timestamp);
    var hour = parseInt(now / 3600);
    var minute = parseInt((now - 3600 * hour) / 60);
    var second = now - 3600 * hour - 60 * minute;
    hour = hour < 10 ? '0' + (hour) : hour;
    minute = minute < 10 ? '0' + (minute) : minute;
    second = second < 10 ? '0' + (second) : second;
    return hour + ":" + minute + ":" + second;
}
26、日期转当前日期零点起的时间戳
function formatDateUnixCur(time) {
    var arg=time.split(":");
    var t1 = parseInt(arg[0]) * 3600;
    var t2 = parseInt(arg[1]) * 60;
    var t3 = parseInt(arg[2]);
    var times = t1+t2+t3;

    return times;
}
27、日期字符串转正常日期格式
function formatDateTime(tm) {
    var time = '';
    if(tm)
    {
        time = tm.substr(0,4) + '-'
            + tm.substr(4,2)+ '-'
            + tm.substr(6,2)+ ' '
            + tm.substr(8,2)+ ':'
            + tm.substr(10,2)+ ':'
            + tm.substr(12,2);
    }
    return time;
}
28、格式化浏览器转义字符
function formatEncodeHtml(value, row, index) {
    var s = value;
    var REGX_HTML_ENCODE = /"|&|'|<|>|[\x00-\x20]|[\x7F-\xFF]|[\u0100-\u2700]/g;
    return (typeof s != "string") ? s :
        s.replace(REGX_HTML_ENCODE,
        function ($0) {
            var c = $0.charCodeAt(0), r = ["&#"];
            c = (c == 0x20) ? 0xA0 : c;
            r.push(c);
            r.push(";");
            return r.join("");
        });
}   
29、其他校验
const ipv4Reg = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/im;

const ipv4rangeReg = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2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-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]d|1dd|[1-9]?d)(.(25[0-5]|2[0-4]d|1dd|[1-9]?d)){3}))|:)))(%.+)?s*(\/(d|dd|1[0-1]d|12[0-8]))$/im;	
30、根据某个属性给object数组进行排序
 function keyNameSort(keyName){
 		return function (obj1,obj2){
 			var v1 = obj1[keyName];
 			var v2 = obj2[keyName];
 			if(v1>v2)return 1;
 			else if(v1==v2)return 0;
 			else return -1;
 		}
  }
  function foo(arr,keyName){
 		arr.sort(keyNameSort(keyName));
 }  
31、利用JavaScript打印出Fibonacci数(不使用全局变量
(function () {
	var outLength = 20, nowValue = 0, prevValue = 1, swapValue;
	for (var i = 1, len = outLength - 1; i < len; i++) {
		if (i < 3) {
			nowValue = 1;
		} else {
			swapValue = nowValue + prevValue;
			prevValue = nowValue;
			nowValue = swapValue;
		}
		console.log(nowValue)
	}
}())
32、数组搜索查询某个str
function searchList(str, list) {
	var arr = [];
	if(str){
		if(list.length > 0){
			for(var i=0,len=list.length;i<len;i++){
				if(list[i]){
					var item = list[i];
					if(item.label.toLowerCase().indexOf(str.toLowerCase())> -1){
						arr.push(item);
					}
				}
			}
    	}
	}
	return arr;
}
33、以天时分的格式计时
//计算差值----毫秒数 
var haveTime =(new Date()) - (new Date("2018-05-25 20:35:48")); 

//将时间戳转为天时分格式
function getTimer(haveTime){ 
  var days = parseInt(haveTime / 1000 / 60 / 60 / 24 , 10); //计算上线的天数 
  var hours = parseInt(haveTime / 1000 / 60 / 60 % 24 , 10); //计算上线的小时 
  var minutes = parseInt(haveTime / 1000 / 60 % 60, 10);//计算上线的分钟 
  // var seconds = parseInt(haveTime / 1000 % 60, 10);//计算上线的秒数 
  days = checkTime(days); 
  hours = checkTime(hours); 
  minutes = checkTime(minutes); 
  // seconds = checkTime(seconds); 
  return days+"天" + hours+"小时" + minutes+"分";  
} 
function checkTime(i){ //将0-9的数字前面加上0,例1变为01 
  if(i<10) 
  { 
    i = "0" + i; 
  } 
  return i; 
}

//从元素获取值(天时分),以天时分的格式计时并赋值给该元素
function setTiem() {
	$('tbody tr td:last-child').each(function(index,item){
		var strTiem = $(item).text();
		if(strTiem){
			var days = parseInt(strTiem.slice(0,2));
			var hours = parseInt(strTiem.slice(3,5));
			var minutes = parseInt(strTiem.slice(7,9));
			minutes++;
			if(minutes >= 60){
				minutes = 0;
				hours ++;
			}
			if(hours >= 24){
				hours = 0;
				days ++;
			}
			days = checkTime(days); 
			hours = checkTime(hours); 
			minutes = checkTime(minutes);
			$(item).text(days+"天" + hours+"小时" + minutes+"分");
		}
	})
}