Home > Web Front-end > JS Tutorial > body text

Summary of commonly used JS verification and functions_Basic knowledge

WBOY
Release: 2016-05-16 16:24:49
Original
947 people have browsed it

The following are some JS verifications and functions that I commonly use. Some verifications are directly written into the properties of the object and can be called directly through the object.method

Copy code The code is as follows:

//Floating point division operation
function fdiv(a, b, n) {
If (n == undefined) { n = 2; }
var t1 = 0, t2 = 0, r1, r2;
Try { t1 = a.toString().split(".")[1].length } catch (e) { }
Try { t2 = b.toString().split(".")[1].length } catch (e) { }
with (Math) {
r1 = Number(a.toString().replace(".", ""));
          r2 = Number(b.toString().replace(".", ""));
          return ((r1 / r2) * pow(10, t2 - t1)).toFixed(n);
}
}

Copy code The code is as follows:

//Floating point multiplication
function fmul(a, b, n) {
If (n == undefined) { n = 2; }
var m = 0, s1 = a.toString(), s2 = b.toString();
Try { m = s1.split(".")[1].length } catch (e) { }
Try { m = s2.split(".")[1].length } catch (e) { }
Return (Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)).toFixed(n);
}

Copy code The code is as follows:

//Floating point addition operation
function fadd(a, b, n) {
If (n == undefined) { n = 2; }
var r1, r2, m;
Try { r1 = a.toString().split(".")[1].length } catch (e) { r1 = 0 }
Try { r2 = b.toString().split(".")[1].length } catch (e) { r2 = 0 }
m = Math.pow(10, Math.max(r1, r2))
Return ((a * m b * m) / m).toFixed(n);
}

Copy code The code is as follows:

//Floating point subtraction operation
function fsub(a, b, n) {
If (n == undefined) { n = 2; }
var r1, r2, m;
Try { r1 = a.toString().split(".")[1].length } catch (e) { r1 = 0 }
Try { r2 = b.toString().split(".")[1].length } catch (e) { r2 = 0 }
m = Math.pow(10, Math.max(r1, r2));
//Dynamic control precision length
//n = (r1 >= r2) ? r1 : r2;
Return ((a * m - b * m) / m).toFixed(n);
}
Number.prototype.add = function (arg) {
Return fadd(this, arg);
}
Number.prototype.subs = function (arg) {
Return fsub(this, arg);
}
Number.prototype.mul = function (arg) {
Return fmul(this, arg);
}
Number.prototype.div = function (arg) {
Return fdiv(this, arg);
}

Copy code The code is as follows:

///Format the number of digits. If the number of digits is insufficient, 0 will be added to the left by default. If parameter 2 is specified and the value of parameter 2 is 1, 0 will be added to the right
Number.prototype.FormatLen = function (len, direct) {
var d = parseInt(direct);
If (isNaN(d)) { d = 0; }
var num = this.toString();
If (num.length < len) {
for (var i = num.length; i < len; i ) {
                 if (d == 0) {
                num = "0" num;
            }
             else {
               num = "0";
            }
}
}
Return num;
}

Copy code The code is as follows:

//Format decimal point digits, you can specify the number of decimal places, whether to round, and other parameters
Number.prototype.FormatRadix = function (len, IsRound) {
var num = this.toString();
var numArr = num.split('.');
var rad = 0;
var numpart = parseInt(numArr[0]);
If (numArr.length >= 2) {
If (numArr[1].length < len) {
             rad = parseInt(numArr[1]).FormatLen(len, 1);
}
         else {
If (numArr[1].length == len) {
               rad = numArr[1];
            }
             else {
                 rad = numArr[1].substr(0, len);
                       if (IsRound) {
                  var d = parseInt(numArr[1].substr(len, 1));
if (d >= 5) { rad = 1; if (rad.toString().length > len) { numpart = 1; rad = rad.toString().substr(1, len); } }
                }
            }

}
}
else {
          rad = rad.FormatLen(len);
}
Return numpart "." rad;
}

Copy code The code is as follows:

//Detect whether there are the same elements in the string. split is the string separator. If the separator is specified, it is judged whether the string separated by the separator is repeated. If it is not specified, it is judged whether the single string is repeated
//Return true if there are duplicates
String.prototype.CompareElement = function (s) {
var str = this.toString();
If (s == undefined) {
for (var i = 0; i < str.length; i ) {
for (j = i 1; j < str.length; j ) {
If (str.substr(i, 1) == str.substr(j, 1)) {
                         return true;
                }
            }
}
}
else {
var strArr = str.split(s);
for (var i = 0; i < strArr.length; i ) {
for (var j = i 1; j < strArr.length; j ) {
If (strArr[i] == strArr[j]) {
                         return true;
                }
            }
}
}
Return false;
}
String.prototype.replaceAll = function (str, tostr) {
oStr = this;
While (oStr.indexOf(str) > -1) {
oStr = oStr.replace(str, tostr);
}
Return oStr;
}
Array.prototype.CompareElement = function () {
var strArr = this;
for (var i = 0; i < strArr.length; i ) {
for (var j = i 1; j < strArr.length; j ) {
If (strArr[i] == strArr[j]) {
                   return true;
            }
}
}
Return false;
}

Copy code The code is as follows:

//The number of strings to be converted into groups. If the delimiter s is not specified, the delimiter will be separated by, by default. If the specified delimiter is empty, each character will be treated as an array element
String.prototype.ToArray = function (s) {
If (s == undefined) { s = ","; }
var strArr = [];
​ strArr = this.split(s);
Return strArr;
}

Copy code The code is as follows:

//Convert an array to a string. All elements are connected using the specified delimiter. The default delimiter is,
Array.prototype.ToIDList = function (s) {
If (s == undefined) { s = ","; }
var list = "";
for (var i = 0; i < this.length; i ) {
list = (list == "" ? this[i] : s "" this[i]);
}
Return list;
}

Copy code The code is as follows:

//Get the position index of the specified element. If the element does not exist, return -1
Array.prototype.GetIndex = function (s) {
var index = -1;
for (var i = 0; i < this.length; i ) {
If ((s "") == this[i]) {
index = i;
}
}
Return index;
}

Copy code The code is as follows:

//Delete the specified element from the array
Array.prototype.Remove = function (s) {
var list = "";
for (var i = 0; i < this.length; i ) {
If (s != this[i]) {
list = (list == "" ? this[i] : "," this[i]);
}
}
Return list.ToArray();
}

Copy code The code is as follows:

/// Sort the array numerically asc specifies whether to sort in ascending order, which can be true or false, ascending order is not specified
Array.prototype.SortByNumber = function (asc) {
If (asc == undefined) { asc = true; }
If (asc) {
          return this.sort(SortNumberAsc);
}
else {
          return this.sort(SortNumberDesc);
}
}
Array.prototype.InArray = function (e) {
var IsIn = false;
for (var i = 0; i < this.length; i ) {
If (this[i] == (e "")) {
IsIn = true;
}
}
Return IsIn;
}
String.prototype.Trim = function (s) { return Trim(this, s); }
String.prototype.LTrim = function (s) { return LTrim(this, s); }
String.prototype.RTrim = function (s) { return RTrim(this, s); }
//Use with Array.SortByNumer to sort the numbers in descending order
function SortNumberDesc(a, b) {
Return b - a;
}
//Use with Array.SortByNumer to sort the numbers in ascending order
function SortNumberAsc(a, b) {
Return a - b;
}
//This is an independent function
function LTrim(str, s) {
If (s == undefined) { s = " "; }
If (str == s && s != " ") { return s; }
var i;
for (i = 0; i < str.length; i ) {
If (str.charAt(i) != s && str.charAt(i) != s) break;
}
 str = str.substring(i, str.length);
Return str;
}
function RTrim(str, s) {
var i;
If (str == s && s != " ") { return s; }
If (s == undefined) { s = " "; }
for (i = str.length - 1; i >= 0; i--) {
If (str.charAt(i) != s && str.charAt(i) != s) break;
}
 str = str.substring(0, i 1);
Return str;
}
function Trim(str, s) {
Return LTrim(RTrim(str, s), s);
}

Copy code The code is as follows:

///Check whether the string is composed of Chinese, English, numbers and underscores
function chkNickName(str) {
var pattern = /^[wu4e00-u9fa5] $/gi;
If (pattern.test(str)) {
        return true;
}
Return false;
}

Copy code The code is as follows:

//Judge the length (the length is not limited to 0)
String.prototype.IsLen = function () {
var isRightFormat = false;
var minnum = arguments[0] ? arguments[0] : 0;
var maxnum = arguments[1] ? arguments[1] : 0;
isRightFormat = (minnum == 0 && maxnum == 0 ? true : (calculate_byte(this) >= minnum && calculate_byte(this) <= maxnum ? true : false));
Return isRightFormat;
}

Copy code The code is as follows:

//Verify whether the string is alphanumeric _ -
String.prototype.IsStr = function () {
var myReg = /^[0-9a-zA-Z-_] $/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify username
String.prototype.IsUsername = function () {
var myReg = /^[0-9a-zA-Z-_]{3,50}$/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify password
String.prototype.IsPassword = function () {
var myReg = /^[0-9a-zA-Z`~!@#$%^&*()-_ ={}[];:"'?/\]{6,}$/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify whether it is a letter
String.prototype.IsEn = function () {
var myReg = /^[a-zA-Z] $/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify whether it is a Chinese character
String.prototype.IsCn = function () {
var myReg = /^[u0391-uFFE5] $/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify E-mail
String.prototype.IsEmail = function () {
var myReg = /([w-.] )@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)| (([w-] .) ))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify MSN
String.prototype.IsMSN = function () {
var myReg = /([w-.] )@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)| (([w-] .) ))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify QQ number
String.prototype.IsQQ = function () {
var myReg = /^[1-9]d{4,10}$/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify URL
String.prototype.IsHttpUrl = function () {
var myReg = /^http://[A-Za-z0-9] .[A-Za-z0-9] [/=?%-&_~`@[]': !]*([^< >""])*$/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify domain name
String.prototype.IsDoMainName = function () {
var myReg = /^[0-9a-zA-Z]([0-9a-zA-Z-] .){1,3}[a-zA-Z]{2,4}?$/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify IPV4 address
String.prototype.IsIpv4 = function () {
var myReg = /^(2[0-5]{2}|1?[0-9]{1,2}).(2[0-5]{2}|1?[0-9]{1 ,2}).(2[0-5]{2}|1?[0-9]{1,2}).(2[0-5]{2}|1?[0-9]{1 ,2})$/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify image address (images dynamically generated by CGI are not supported)
String.prototype.IsImgURL = function () {
var myReg = /^.(jpeg|jpg|gif|bmp|png|pcx|tiff|tga|lwf)$/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify mobile phone number
String.prototype.IsCellPhone = function () {
var myReg = /^(((d{3}))|(d{3}-))?1[3,5]d{9}$/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify landline number
String.prototype.IsPhone = function () {
var myReg = /^[ ]{0,1}(d){1,3}[ ]?([-]?((d)|[ ]){1,12}) $/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify zip code
String.prototype.IsZipCode = function () {
var myReg = /[0-9]{6}/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify ID number
String.prototype.IsIdCard = function () {
var myReg = /(^([d]{15}|[d]{18}|[d]{17}[xX]{1})$)/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify date format YY-MM-DD
String.prototype.IsDateFormat = function () {
var myReg = /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify time format HH:MM:SS
String.prototype.IsRangeTime = function () {
var myReg = /^(d{2}):(d{2}):(d{2})$/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify amount format
String.prototype.IsMoney = function () {
var myReg = /^[0-9]{1,8}[.]{0,1}[0-9]{0,6}$/;
If (myReg.test(this)) return true;
Return false;
}

Copy code The code is as follows:

//Verify the digital format and determine the range of the number (min: minimum value; max: maximum value.)
String.prototype.IsInt = function () {
var isRightFormat = false;
var minnum = arguments[0] ? arguments[0] : 0;
var maxnum = arguments[1] ? arguments[1] : 0;
var myReg = /^[- ]?d $/;
If (myReg.test(this)) {
isRightFormat = (minnum == 0 && maxnum == 0 ? true : (this > minnum && this < maxnum ? true : false));
}
Return isRightFormat;
}

Copy code The code is as follows:

//Verify search keywords
String.prototype.IsSearch = function () {
var myReg = /^[|"'<>,.*&@#$;:!^()]/;
If (myReg.test(this)) return false;
Return true;
}

Copy code The code is as follows:

//js accurately calculates the string length
function calculate_byte(sTargetStr) {
var sTmpStr, sTmpChar;
var nOriginLen = 0;
var nStrLength = 0;

sTmpStr = new String(sTargetStr);
nOriginLen = sTmpStr.length;

for (var i = 0; i < nOriginLen; i ) {
        sTmpChar = sTmpStr.charAt(i);

if (escape(sTmpChar).length > 4) {
nStrLength = 2;
            } else if (sTmpChar != 'r') {
               nStrLength ;
}
}

return nStrLength;
}

Copy code The code is as follows:

//Color value;
String.prototype.IsColor = function () {
var s = arguments[0] ? arguments[0] : "";
s = s.Trim();
If (s.length != 7) return false;
Return s.search(/#[a-fA-F0-9]{6}/) != -1;
}

Copy code The code is as follows:

//js日期格式化
Date.prototype.format = function (format) {
    var o = {
        "M ": this.getMonth() 1, //month
        "d ": this.getDate(), //day
        "h ": this.getHours(), //hour
        "m ": this.getMinutes(), //minute
        "s ": this.getSeconds(), //second
        "q ": Math.floor((this.getMonth() 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }

    if (/(y )/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" k ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" o[k]).substr(("" o[k]).length));
        }
    }
    return format;
}

function HasChinese(value) {
    if (/^[u4e00-u9fa5] $/.test(value)) {
        return true;
    }
    return false;
}

function ToDate(dateStr) {
    var dStr = dateStr.toString();
    dateStr = dStr.replaceAll("-", "/");

    return new Date(Date.parse(dateStr));
}

复制代码 代码如下:

//是否ID列表
String.prototype.IsIdList = function (s) {
    if (s == undefined) {
        s = ",";
    }
    var arr = this.split(s);
    for (var i = 0; i < arr.length; i ) {
        if (isNaN(parseInt(arr[i]))) { return false; }
    }
    return true;
}

复制代码 代码如下:

//获取事件触发的对象
function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement;

代码都很简洁,简单,功能却都很实用,有需要的小伙伴参考下

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template