Verification and data processing

Keywords: ftp Mac JSON Attribute

Verification and data processing

1. URL verification
    // 1. verify url
	function isURL(str_url) {
		var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
		+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" // user@ of ftp
		+ "(([0-9]{1,3}\.){3}[0-9]{1,3}" // URL in IP form - 199.194.52.184
		+ "|" // Allow IP and DOMAIN
		+ "([0-9a-z_!~*'()-]+\.)*" // Domain name - www.
		+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // Two level domain name
		+ "[a-z]{2,6})" // first level domain- .com or .museum
		+ "(:[0-9]{1,4})?" // Port: 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
    //For example, http://www.baidu.com
    var REG_URL = /^(http?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
    
	//3. URL (without http/https)
    //For example: www.baidu.com
	var URL_REG  = /^([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;

2. Port number verification
//Verify ip, ip: Port
function testServerList(str){
	//IP address 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, figures
//positive integer
var NUM = /^[1-9]\d*$/;
//integer
VAR REG = /^([\d]+)$/
//Integers and floats
var reg = /^\d+(?=\.{0,1}\d+$|$)/;
4. Host name
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
Method 1:
//mac address format
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}$/;
Method 2:
const macReg = /^(([a-f0-9]{2}:)|([a-f0-9]{2}-)){5}[a-f0-9]{2}$/im;
6. Including Chinese
var reg = /[\u4e00-\u9fa5]/
7. Date or not
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. Time
isTime: function (s) {
    s = sort.trim(s);
    var re = /^(\d\d):([0-5][0-9]):([0-5][0-9])$/;
    return re.test(s);
},     
9. Calculate the number of characters
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. Check whether the string is empty
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. Judge whether the object is empty
function isEmptyObject(e) {
    var t;
    for (t in e)
        return !1;
    return !0
}
12. Check ip range
function compareIsEqualIp(ipBegin, ipEnd){
    var temp1;
    var temp2;
    temp1 = ipBegin.split(".");
    temp2 = ipEnd.split(".");

    if(ipBegin === ipEnd) {
    	top.$.tips("Start IP Can't and end IP Agreement");
    	return false;
    }

    for (var i = 0; i < 3; i++)  {
        if (parseInt(temp1[i]) != parseInt(temp2[i])){
        	top.$.tips("Top three must be the same");
            return false;
            break;
        }
    }
    return true;
}
13. Deep copy
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. Check whether the numbers in the two arrays have the same data
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. Judge whether there is duplicate data in an array
function isRepeat(arr){
    var hash = {};
    for(var i in arr) {
        if(hash[arr[i]])
            return true;
        hash[arr[i]] = true;
    }
     return false;
}
17. Array de duplication
 //Method 1
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;
}
 //Method two
function removal(arr){
    var res = [];
    res = arr.filter(function(item){
        return res.filter(d => d.id == item.id)[0] ? '' :res.push(item);
    });
    return res;
}
//Method three
/**
 * Filter the null values in the JS array and return the new array
 * @param array Array to filter
 * @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 method
//Method 1
var item = subtypelist.filter(function(item, index) {

	return item.type == type;
});
//Method two
var item = subtypelist.filter(d => d.type == type)[0].data;
//Remove empty array, empty string, undefined, null
var newArr = arr.filter(item => item);    
19. Input start and end to generate an array
function makeArr(start,end){
	var arr = [];
	if(end >= start){
		for (var i = start; i <= end; i++) {
			arr.push(i)
		}
	}
	return arr
}
20. Change the port segment in the port number to port
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] = '';
			}
		}
	}
	// Generate clean array
	var reg = /[\d\.]+\,([\d\.]+)/g;
	newArr = arr.join(",").split(",");
	// Duplicate removal
	newArr = Array.Unique(newArr);
	newArr = newArr.sort();

	// Remove the first empty data
	if (newArr[0] == "") {
		newArr.shift()
	}
	return newArr
}
21. IP address comparison size
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. Go to blank
//Left blank space
ltrim: function (s) {
    return s.replace(/^\s*/, "");
},
//Right blank space
rtrim: function (s) {
    return s.replace(/\s*$/, "");
},
//Space on both sides
trim: function (s) {
    return sort.rtrim(sort.ltrim(s));
}
23. Date to time stamp
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. Time stamp transfer date
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. Date from zero on the date of time stamp transfer
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. Time stamp from zero of date to current date
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. Date string to normal date format
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. Format browser escape characters
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. Other verification
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[0-4][0-9]|25[0-5])-(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0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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. Sort the object array according to a certain attribute
 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. Print out Fibonacci number with JavaScript (without using global variables)
(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. Array search query a 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;
}

Posted by backie on Thu, 31 Oct 2019 08:55:24 -0700