Write your own code base

1. Preface

You should know when developing, there are many common examples of operation. For example, array de-duplication, keyword highlighting, disruption of the array and so on. These operations, the code generally will not be many, the realization of logic will not be difficult, the following code, I will not explain too much, with comments, I believe you will understand. However, the use of places will be compared, if there is a project where need to be used, if repeated writing, that is, code sink, development efficiency is not needed, reuse is basically copy and paste! This is a very bad habit, you can consider encapsulating some common operations into functions, when calling, just call directly!

2. String operation

2-1 String Space Removal

//Remove blank type 1-all blanks 2-front and back blanks 3-front blanks 4-back blanks
//Util.trim('  1235asd',1)
//result: 1235asd
//This method has been replaced by the original scheme, but considering that sometimes developing PC stations needs to be IE8-compatible, it is still retained.
trim: function (str, type) {
    switch (type) {
        case 1:
            return str.replace(/\s+/g, "");
        case 2:
            return str.replace(/(^\s*)|(\s*$)/g, "");
        case 3:
            return str.replace(/(^\s*)/g, "");
        case 4:
            return str.replace(/(\s*$)/g, "");
        default:
            return str;
    }
}

2-2 letter case switching

/*type
 1:title case
 2: Home capital lowercase
 3: toggle case
 4: All capitals
 5: lowercase
 * */
//Util.changeCase('asdasd',1)
//result: Asdasd
changeCase: function (str, type) {
    function ToggleCase(str) {
        var itemText = ""
        str.split("").forEach(
            function (item) {
                if (/^([a-z]+)/.test(item)) {
                    itemText += item.toUpperCase();
                } else if (/^([A-Z]+)/.test(item)) {
                    itemText += item.toLowerCase();
                } else {
                    itemText += item;
                }
            });
        return itemText;
    }
    switch (type) {
        case 1:
            return str.replace(/\b\w+\b/g, function (word) {
                return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
            });
        case 2:
            return str.replace(/\b\w+\b/g, function (word) {
                return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase();
            });
        case 3:
            return ToggleCase(str);
        case 4:
            return str.toUpperCase();
        case 5:
            return str.toLowerCase();
        default:
            return str;
    }
}

2-3 String Cyclic Copy

//RepeatStr (str - > string, count - > number of times)
//Util.repeatStr('123',3)
//"result: 123123123"
repeatStr: function (str, count) {
    var text = '';
    for (var i = 0; i < count; i++) {
        text += str;
    }
    return text;
}

2-4 String Replacement

replaceAll: function (str, AFindText, ARepText) {
    raRegExp = new RegExp(AFindText, "g");
    return str.replace(raRegExp, ARepText);
}

2-5 replacement *

//Character substitution*
//ReplceStr (String, Character Format, Replacement Method, Replacement Character (Default*))
//Util.replaceStr('18819322663',[3,5,3],0)
//result: 188*****663
//Util.replaceStr('asdasdasdaa',[3,5,3],1)
//result: ***asdas***
//Util.replaceStr('1asd88465asdwqe3',[5],0)
//result: *****8465asdwqe3
//Util.replaceStr('1asd88465asdwqe3',[5],1,'+')
//result: "1asd88465as+++++"
replaceStr: function (str, regArr, type, ARepText) {
    var regtext = '',
        Reg = null,
        replaceText = ARepText || '*';
    //RepatStr is defined above (string circular replication). Attention, everybody.
    if (regArr.length === 3 && type === 0) {
        regtext = '(\\w{' + regArr[0] + '})\\w{' + regArr[1] + '}(\\w{' + regArr[2] + '})'
        Reg = new RegExp(regtext);
        var replaceCount = this.repeatStr(replaceText, regArr[1]);
        return str.replace(Reg, '$1' + replaceCount + '$2')
    }
    else if (regArr.length === 3 && type === 1) {
        regtext = '\\w{' + regArr[0] + '}(\\w{' + regArr[1] + '})\\w{' + regArr[2] + '}'
        Reg = new RegExp(regtext);
        var replaceCount1 = this.repeatStr(replaceText, regArr[0]);
        var replaceCount2 = this.repeatStr(replaceText, regArr[2]);
        return str.replace(Reg, replaceCount1 + '$1' + replaceCount2)
    }
    else if (regArr.length === 1 && type === 0) {
        regtext = '(^\\w{' + regArr[0] + '})'
        Reg = new RegExp(regtext);
        var replaceCount = this.repeatStr(replaceText, regArr[0]);
        return str.replace(Reg, replaceCount)
    }
    else if (regArr.length === 1 && type === 1) {
        regtext = '(\\w{' + regArr[0] + '}$)'
        Reg = new RegExp(regtext);
        var replaceCount = this.repeatStr(replaceText, regArr[0]);
        return str.replace(Reg, replaceCount)
    }
}

2-6 Detection String

//Detection string
//Util.checkType('165226226326','phone')
//result: false
//You can expand as needed.
checkType: function (str, type) {
    switch (type) {
        case 'email':
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
        case 'phone':
            return /^1[3|4|5|7|8][0-9]{9}$/.test(str);
        case 'tel':
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
        case 'number':
            return /^[0-9]$/.test(str);
        case 'english':
            return /^[a-zA-Z]+$/.test(str);
        case 'text':
            return /^\w+$/.test(str);
        case 'chinese':
            return /^[\u4E00-\u9FA5]+$/.test(str);
        case 'lower':
            return /^[a-z]+$/.test(str);
        case 'upper':
            return /^[A-Z]+$/.test(str);
        default:
            return true;
    }
}

2-7 Detection of Password Strength

//Util.checkPwd('12asdASAD')
//result: 3 (strength grade 3)
checkPwd: function (str) {
    var nowLv = 0;
    if (str.length < 6) {
        return nowLv
    }
    if (/[0-9]/.test(str)) {
        nowLv++
    }
    if (/[a-z]/.test(str)) {
        nowLv++
    }
    if (/[A-Z]/.test(str)) {
        nowLv++
    }
    if (/[\.|-|_]/.test(str)) {
        nowLv++
    }
    return nowLv;
}

2-8 random code (toString detail)

//count range 0-36
//Util.randomWord(10)
//result: "2584316588472575"
//Util.randomWord(14)
//result: "9b405070dd00122640c192caab84537"
//Util.randomWord(36)
//result: "83vhdx10rmjkyb9"
randomWord: function (count) {
    return Math.random().toString(count).substring(2);
}

2-9 Find Strings

Maybe the title will be a bit misleading. Let me briefly describe a requirement to find out the number of'blog'in the string'sad44654 blog 5A 1sd67as 9dablog 4S 5D 16zxc4sdweasjk blog wqepaskdkblog gahseiuadbhjcibloyeajzxkcabuyizwezc967'. The code is as follows

//var strTest='sad44654blog5a1sd67as9dablog4s5d16zxc4sdweasjkblogwqepaskdkblogahseiuadbhjcibloguyeajzxkcabloguyiwezxc967'
//Util.countStr(strTest,'blog')
//result: 6
countStr: function (str, strSplit) {
    return str.split(strSplit).length - 1
}

2-10 filter string

//Filter strings (html tags, expressions, special characters)
//Strings, replacement content (special-special characters, html-html tags, emjoy-emjoy expressions, word-lowercase letters, WORD-uppercase letters, number-digits, chinese-Chinese), what to replace, default', which special characters to retain
//If multiple characters need to be filtered, the type parameter is used to segment, as follows: chestnuts
//The html tags, capital letters, Chinese characters and special characters of the filtered string are all replaced by *, but the special characters'%','?', except these two, all other special characters are cleared.
//Var str='asd 654a Big Stupid Sasdasd ASDQWEXZC6d5%^* ^ & ^%& *$\"\\\\\\\\\\\\\
// Util.filterStr(str,'html,WORD,chinese,special','*','%?')
//result: "asd    654a**sasdasd*********6d5#%^*^&*^%^&*$\"'#@!()*/-())_'":"{}?*****************"
filterStr: function (str, type, restr, spstr) {
    var typeArr = type.split(','), _str = str;
    for (var i = 0, len = typeArr.length; i < len; i++) {
        //Is it filtering special symbols?
        if (typeArr[i] === 'special') {
            var pattern, regText = '$()[]{}?\|^*+./\"\'+';
            //Are there any special symbols that need to be retained?
            if (spstr) {
                var _spstr = spstr.split(""), _regText = "[^0-9A-Za-z\\s";
                for (var j = 0, len1 = _spstr.length; j < len1; j++) {
                    if (regText.indexOf(_spstr[j]) === -1) {
                        _regText += _spstr[j];
                    }
                    else {
                        _regText += '\\' + _spstr[j];
                    }
                }
                _regText += ']'
                pattern = new RegExp(_regText, 'g');
            }
            else {
                pattern = new RegExp("[^0-9A-Za-z\\s]", 'g')
            }
        }
        var _restr = restr || '';
        switch (typeArr[i]) {
            case 'special':
                _str = _str.replace(pattern, _restr);
                break;
            case 'html':
                _str = _str.replace(/<\/?[^>]*>/g, _restr);
                break;
            case 'emjoy':
                _str = _str.replace(/[^\u4e00-\u9fa5|\u0000-\u00ff|\u3002|\uFF1F|\uFF01|\uff0c|\u3001|\uff1b|\uff1a|\u3008-\u300f|\u2018|\u2019|\u201c|\u201d|\uff08|\uff09|\u2014|\u2026|\u2013|\uff0e]/g, _restr);
                break;
            case 'word':
                _str = _str.replace(/[a-z]/g, _restr);
                break;
            case 'WORD':
                _str = _str.replace(/[A-Z]/g, _restr);
                break;
            case 'number':
                _str = _str.replace(/[0-9]/g, _restr);
                break;
            case 'chinese':
                _str = _str.replace(/[\u4E00-\u9FA5]/g, _restr);
                break;
        }
    }
    return _str;
}

2-11 Formatting Processing Strings

//Util.formatText('1234asda567asd890')
//result: "12,34a,sda,567,asd,890"
//Util.formatText('1234asda567asd890',4,' ')
//result: "1 234a sda5 67as d890"
//Util.formatText('1234asda567asd890',4,'-')
//result: "1-234a-sda5-67as-d890"
formatText: function (str, size, delimiter) {
    var _size = size || 3, _delimiter = delimiter || ',';
    var regText = '\\B(?=(\\w{' + _size + '})+(?!\\w))';
    var reg = new RegExp(regText, 'g');
    return str.replace(reg, _delimiter);
}

2-12 Find the longest word

//Util.longestWord('Find the Longest word in a String')
//result: 7
//Util.longestWord('Find|the|Longest|word|in|a|String','|')
//result: 7
longestWord: function (str, splitType) {
    var _splitType = splitType || /\s+/g,
        _max = 0,_item='';
    var strArr = str.split(_splitType);
    strArr.forEach(function (item) {
        if (_max < item.length) {
            _max = item.length
            _item=item;
        }
    })
    return {el:_item,max:_max};
}

Capitalize the first letter of a word in 2-13 sentences

//I've been struggling with this. Even if the first letter is capitalized, the first letter of every word may not be capitalized, but I don't know which should be capitalized and which shouldn't be capitalized.
//Util.titleCaseUp('this is a title')
//"This Is A Title"
titleCaseUp: function (str, splitType) {
    var _splitType = splitType || /\s+/g;
    var strArr = str.split(_splitType),
        result = "", _this = this
    strArr.forEach(function (item) {
        result += _this.changeCase(item, 1) + ' ';
    })
    return this.trim(result, 4)
}  

3. Array operations

3-1 array de-weighting

removeRepeatArray: function (arr) {
    return arr.filter(function (item, index, self) {
        return self.indexOf(item) === index;
    });
}

3-2 Array Sequence Disturbance

upsetArr: function (arr) {
    return arr.sort(function () {
        return Math.random() - 0.5
    });
},

3-3 Array Maximum and Minimum

//Array Maximum
maxArr: function (arr) {
    return Math.max.apply(null, arr);
},
//Array Minimum
minArr: function (arr) {
    return Math.min.apply(null, arr);
}

3-4 array summation, average

//The encapsulation of this block is mainly for arrays of digital type.
//Summation
sumArr: function (arr) {
    return arr.reduce(function (pre, cur) {
        return pre + cur
    })
}
//Array average, decimal point may have many bits, here do not deal with, processing is not flexible!
covArr: function (arr) {
    return this.sumArr(arr) / arr.length;
},

3-5 Random Access to Elements from Arrays

//Util.randomOne([1,2,3,6,8,5,4,2,6])
//2
//Util.randomOne([1,2,3,6,8,5,4,2,6])
//8
//Util.randomOne([1,2,3,6,8,5,4,2,6])
//8
//Util.randomOne([1,2,3,6,8,5,4,2,6])
//1
randomOne: function (arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

3-6 Returns the number of occurrences of an element in an array (string)

//Util.getEleCount('asd56+asdasdwqe','a')
//result: 3
//Util.getEleCount([1,2,3,4,5,66,77,22,55,22],22)
//result: 2
getEleCount: function (obj, ele) {
    var num = 0;
    for (var i = 0, len = obj.length; i < len; i++) {
        if (ele === obj[i]) {
            num++;
        }
    }
    return num;
}

3-7 Returns the most elements and occurrences of arrays (strings)

//Arr, rank - > length, default array length, rank type, sort mode, default descending order
//Return value: el - > element, count - > number of times
//Util.getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2])
//By default, return the number of occurrences of all elements
//result: [{"el":"2","count":6},{"el":"1","count":4},{"el":"3","count":2},{"el":"4","count":1},{"el":"5","count":1},{"el":"6","count":1}]
//Util.getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3)
//Reference (rank=3), returning only the first three ranks of occurrences
//result: [{"el":"2","count":6},{"el":"1","count":4},{"el":"3","count":2}]
//Util.getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],null,1)
//Rank type = 1, rank = null, ascending order returns the number of occurrences of all elements
//result: [{"el":"6","count":1},{"el":"5","count":1},{"el":"4","count":1},{"el":"3","count":2},{"el":"1","count":4},{"el":"2","count":6}]
//Util.getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3,1)
//Reference (rank=3, ranktype=1) returns only the first three of the occurrence order (ascending order)
//result: [{"el":"6","count":1},{"el":"5","count":1},{"el":"4","count":1}]
getCount: function (arr, rank, ranktype) {
    var obj = {},
        k, arr1 = []
    //Record the number of occurrences of each element
    for (var i = 0, len = arr.length; i < len; i++) {
        k = arr[i];
        if (obj[k]) {
            obj[k]++;
        } else {
            obj[k] = 1;
        }
    }
    //Save the result {el-'element', count-number of occurrences}
    for (var o in obj) {
        arr1.push({el: o, count: obj[o]});
    }
    //Sorting (descending)
    arr1.sort(function (n1, n2) {
        return n2.count - n1.count
    });
    //If ranktype is 1, the array is in ascending order and inverted
    if (ranktype === 1) {
        arr1 = arr1.reverse();
    }
    var rank1 = rank || arr1.length;
    return arr1.slice(0, rank1);
}

3-8 Gets an array of n1-n2 Subscripts

//Util.getArrayNum([0,1,2,3,4,5,6,7,8,9],5,9)
//result: [5, 6, 7, 8, 9]
//getArrayNum([0,1,2,3,4,5,6,7,8,9],2)// / does not pass the second parameter and returns the element from n1 to the end of the array by default
//result: [2, 3, 4, 5, 6, 7, 8, 9]
getArrayNum: function (arr, n1, n2) {
    return arr.slice(n1, n2);
}

3-9 filter array

//Delete an array element with a value of'val'
//Util.removeArrayForValue(['test','test1','test2','test','aaa'],'test',')
//result: ["aaa"] With'test'deleted
//Util.removeArrayForValue(['test','test1','test2','test','aaa'],'test')
//result: ["test1", "test2", "aaa"]// The value of the array element is all equal to'test'before it is deleted.
removeArrayForValue: function (arr, val, type) {
    return arr.filter(function (item) {
        return type ? item.indexOf(val) === -1 : item !== val
    })
}

3-10 Gets Some Items of Object Array

//var arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}]
//Util.getOptionArray(arr,'a,c')
//result: [{a:1,c:9},{a:2,c:5},{a:5,c:underfind},{a:4,c:5},{a:4,c:7}]
//Util.getOptionArray(arr,'b')
//result: [2, 3, 9, 2, 5]
getOptionArray: function (arr, keys) {
    var newArr = []
    if (!keys) {
        return arr
    }
    var _keys = keys.split(','), newArrOne = {};
    //Is it just necessary to get the value of an item?
    if (_keys.length === 1) {
        for (var i = 0, len = arr.length; i < len; i++) {
            newArr.push(arr[i][keys])
        }
        return newArr;
    }
    for (var i = 0, len = arr.length; i < len; i++) {
        newArrOne = {};
        for (var j = 0, len1 = _keys.length; j < len1; j++) {
            newArrOne[_keys[j]] = arr[i][_keys[j]]
        }
        newArr.push(newArrOne);
    }
    return newArr
}

3-11 Excludes Some Items of Object Array

//var arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}]
//Util.filterOptionArray(arr,'a')
//result: [{b:2,c:9},{b:3,c:5},{b:9},{b:2,c:5},{b:5,c:7}]
//Util.filterOptionArray(arr,'a,c')
//result: [{b:2},{b:3},{b:9},{b:2},{b:5}]
filterOptionArray: function (arr, keys) {
    var newArr = []
    var _keys = keys.split(','), newArrOne = {};
    for (var i = 0, len = arr.length; i < len; i++) {
        newArrOne = {};
        for (var key in arr[i]) {
            //If key does not exist in excluding keys, add data
            if (_keys.indexOf(key) === -1) {
                newArrOne[key] = arr[i][key];
            }
        }
        newArr.push(newArrOne);
    }
    return newArr
}

3-12 Object Array Sorting

//var arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}]
//Util.arraySort(arr,'a,b')a is the first sorting condition and B is the second sorting condition.
//result: [{"a":1,"b":2,"c":9},{"a":2,"b":3,"c":5},{"a":4,"b":2,"c":5},{"a":4,"b":5,"c":7},{"a":5,"b":9}]
arraySort: function (arr, sortText) {
    if (!sortText) {
        return arr
    }
    var _sortText = sortText.split(',').reverse(), _arr = arr.slice(0);
    for (var i = 0, len = _sortText.length; i < len; i++) {
        _arr.sort(function (n1, n2) {
            return n1[_sortText[i]] - n2[_sortText[i]]
        })
    }
    return _arr;
}

3-13 Array Flattening

//Util.steamroller([1,2,[4,5,[1,23]]])
//[1, 2, 4, 5, 1, 23]
steamroller: function (arr) {
    var newArr = [],_this=this;
    for (var i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            // If it's an array, call (recursively) steamroller to flatten it
            // Then push to newArr
            newArr.push.apply(newArr, _this.steamroller(arr[i]));
        } else {
            // Instead of push ing arrays directly into newArr
            newArr.push(arr[i]);
        }
    }
    return newArr;
}

4. Basic DOM operations

This part of the code actually refers to some functions of jquery, the only difference is that the call is not used, the parameters are the same.
For example, the chestnuts below

//Setting Object Content
jquery: $('#xxx').html('hello world');
//Now: Util.html(document.getElementById('xxx'),'hello world')
//Getting object content
jquery: $('#xxx').html();
//Now: Util.html(document.getElementById('xxx'))

4-1 checks whether the object has any class name

//Check whether the object has any class name
hasClass: function (obj, classStr) {
    if (obj.className && this.trim(obj.className, 1) !== "") {
        var arr = obj.className.split(/\s+/); //This regular expression is because classes can have multiple classes to determine whether they contain
        return (arr.indexOf(classStr) == -1) ? false : true;
    }
    else {
        return false;
    }
}

4-2 Add Class Name

addClass: function (obj, classStr) {
    if ((this.istype(obj, 'array') || this.istype(obj, 'elements')) && obj.length >= 1) {
        for (var i = 0, len = obj.length; i < len; i++) {
            if (!this.hasClass(obj[i], classStr)) {
                obj[i].className += " " + classStr;
            }
        }
    }
    else {
        if (!this.hasClass(obj, classStr)) {
            obj.className += " " + classStr;
        }
    }
}

4-3 Delete class names

removeClass: function (obj, classStr) {
    if ((this.istype(obj, 'array') || this.istype(obj, 'elements')) && obj.length > 1) {
        for (var i = 0, len = obj.length; i < len; i++) {
            if (this.hasClass(obj[i], classStr)) {
                var reg = new RegExp('(\\s|^)' + classStr + '(\\s|$)');
                obj[i].className = obj[i].className.replace(reg, '');
            }
        }
    }
    else {
        if (this.hasClass(obj, classStr)) {
            var reg = new RegExp('(\\s|^)' + classStr + '(\\s|$)');
            obj.className = obj.className.replace(reg, '');
        }
    }
}

4-4 Replacement Class Name ("Substituted Class Name", "Substituted Class Name")

replaceClass: function (obj, newName, oldName) {
    this.removeClass(obj, oldName);
    this.addClass(obj, newName);
}

4-5 Getting Brother Nodes

//Util.siblings(obj,'#id')
siblings: function (obj, opt) {
    var a = []; //Define an array to store o's sibling elements
    var p = obj.previousSibling;
    while (p) { //The brothers who took o first judged whether there was a previous brotherhood element, and if there was one, they performed p to indicate previous Sibling.
        if (p.nodeType === 1) {
            a.push(p);
        }
        p = p.previousSibling //Finally, assign the last node to p
    }
    a.reverse() //Reverse the order so that the order of the elements is in order.
    var n = obj.nextSibling; //Take o's younger brother again
    while (n) { //Judging whether there is the next brother node n means nextSibling
        if (n.nodeType === 1) {
            a.push(n);
        }
        n = n.nextSibling;
    }
    if (opt) {
        var _opt = opt.substr(1);
        var b = [];//Define an array for storing filter a
        if (opt[0] === '.') {
            b = a.filter(function (item) {
                return item.className === _opt
            });
        }
        else if (opt[0] === '#') {
            b = a.filter(function (item) {
                return item.id === _opt
            });
        }
        else {
            b = a.filter(function (item) {
                return item.tagName.toLowerCase() === opt
            });
        }
        return b;
    }
    return a;
}

4-6 Setting Style

css: function (obj, json) {
    for (var attr in json) {
        obj.style[attr] = json[attr];
    }
}

4-7 Setting Text Content

html: function (obj) {
    if (arguments.length === 1) {
        return obj.innerHTML;
    } else if (arguments.length === 2) {
        obj.innerHTML = arguments[1];
    }
}
text: function (obj) {
    if (arguments.length === 1) {
        return obj.innerHTML;
    } else if (arguments.length === 2) {
        obj.innerHTML = this.filterStr(arguments[1],'html');
    }
}

4-8 Display Hiding

show: function (obj) {
    var blockArr=['div','li','ul','ol','dl','table','article','h1','h2','h3','h4','h5','h6','p','hr','header','footer','details','summary','section','aside','']
    if(blockArr.indexOf(obj.tagName.toLocaleLowerCase())===-1){
        obj.style.display ='inline';
    }
    else{
        obj.style.display ='block';
    }
},
hide: function (obj) {
    obj.style.display = "none";
}

5. Other operations

5-1cookie

//cookie
//Set cookie
setCookie: function (name, value, iDay) {
    var oDate = new Date();
    oDate.setDate(oDate.getDate() + iDay);
    document.cookie = name + '=' + value + ';expires=' + oDate;
},
//Get cookie
getCookie: function (name) {
    var arr = document.cookie.split('; ');
    for (var i = 0; i < arr.length; i++) {
        var arr2 = arr[i].split('=');
        if (arr2[0] == name) {
            return arr2[1];
        }
    }
    return '';
},
//delete cookie
removeCookie: function (name) {
    this.setCookie(name, 1, -1);
},

5-2 Clears an empty property in an object

//Util.filterParams({a:"",b:null,c:"010",d:123})
//Object {c: "010", d: 123}
filterParams: function (obj) {
    var _newPar = {};
    for (var key in obj) {
        if ((obj[key] === 0 ||obj[key] === false|| obj[key]) && obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== '') {
            _newPar[key] = obj[key];
        }
    }
    return _newPar;
}

5-3 Cash Uppercase Conversion Function

//Util.upDigit(168752632)
//result: "Renminbi 100 million Lu Biao pick up ten thousand yuan, Lu Biao pick up three hundred thousand yuan."
//Util.upDigit(1682)
//result: "Renminbi is one hundred and fifty dollars in total"
//Util.upDigit(-1693)
//result: "One hundred yuan is owed to Renminbi, one hundred yuan is owed to Lubai, and three yuan is owed to Lubai."
upDigit: function (n) {
    var fraction = ['horn', 'branch', 'Li'];
    var digit = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
    var unit = [
        ['element', 'ten thousand', 'Billion'],
        ['', 'Ten', 'Bai', 'Thousand']
    ];
    var head = n < 0 ? 'Less than RMB' : 'RMB';
    n = Math.abs(n);
    var s = '';
    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/Zero./, '');
    }
    s = s || 'whole';
    n = Math.floor(n);
    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(Zero.)*Zero $/, '').replace(/^$/, 'Zero') + unit[0][i] + s;
        //s = p + unit[0][i] + s;
    }
    return head + s.replace(/(Zero.)*Zero element/, 'element').replace(/(Zero.)+/g, 'Zero').replace(/^whole $/, 'Zero integer');
} 

5-4 Get and set url parameters

//Setting url parameters
//Util.setUrlPrmt({'a':1,'b':2})
//result: a=1&b=2
setUrlPrmt: function (obj) {
    var _rs = [];
    for (var p in obj) {
        if (obj[p] != null && obj[p] != '') {
            _rs.push(p + '=' + obj[p])
        }
    }
    return _rs.join('&');
},
//Getting url parameters
//Util.getUrlPrmt('test.com/write?draftId=122000011938')
//result: Object{draftId: "122000011938"}
getUrlPrmt: function (url) {
    url = url ? url : window.location.href;
    var _pa = url.substring(url.indexOf('?') + 1),
        _arrS = _pa.split('&'),
        _rs = {};
    for (var i = 0, _len = _arrS.length; i < _len; i++) {
        var pos = _arrS[i].indexOf('=');
        if (pos == -1) {
            continue;
        }
        var name = _arrS[i].substring(0, pos),
            value = window.decodeURIComponent(_arrS[i].substring(pos + 1));
        _rs[name] = value;
    }
    return _rs;
}

5-5 Random Returns a Range of Numbers

//Util.randomNumber(5,10)
//Returns 5-10 random integers, including 5,10
//Util.randomNumber(10)
//Returns 0-10 random integers, including 0,10
//Util.randomNumber()
//Returns a random integer of 0-255, including 0,255
randomNumber: function (n1, n2) {
    if (arguments.length === 2) {
        return Math.round(n1 + Math.random() * (n2 - n1));
    }
    else if (arguments.length === 1) {
        return Math.round(Math.random() * n1)
    }
    else {
        return Math.round(Math.random() * 255)
    }
}

5-6 Following in to produce colour

randomColor: function () {
    //Random Number is the function defined below
    //Writing 1
    //return 'rgb(' + this.randomNumber(255) + ',' + this.randomNumber(255) + ',' + this.randomNumber(255) + ')';
    //Writing 2
    return '#' + Math.random().toString(16).substring(2).substr(0, 6);
    //Writing 3
    //var color='#',_index=this.randomNumber(15);
    //for(var i=0;i<6;i++){
    //color+='0123456789abcdef'[_index];
    //}
    //return color;
}
//Sometimes there are problems with this writing. Everybody should pay attention to it.
//Math.floor(Math.random()*0xffffff).toString(16);

5-7 Date Date Date Date Date Time Part

//Countdown to a certain time
//Util.getEndTime('2017/7/22 16:0:0')
//result: "The remaining time is 6 days, 2 hours, 28 minutes, 20 seconds"
getEndTime: function (endTime) {
    var startDate = new Date(); //Start time, current time
    var endDate = new Date(endTime); //End time, need to pass in time parameter
    var t = endDate.getTime() - startDate.getTime(); //Milliseconds of time difference
    var d = 0,
        h = 0,
        m = 0,
        s = 0;
    if (t >= 0) {
        d = Math.floor(t / 1000 / 3600 / 24);
        h = Math.floor(t / 1000 / 60 / 60 % 24);
        m = Math.floor(t / 1000 / 60 % 60);
        s = Math.floor(t / 1000 % 60);
    }
    return "Remaining time" + d + "day " + h + "hour " + m + " Minute" + s + " second";
}

5-8 adaptation rem

There are many ways to adapt, so I'll write my own way. You can also go to a question I answered to see more detailed instructions! Mobile Adaptation Problem

getFontSize: function (_client) {
    var doc = document,
        win = window;
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            //If the screen is larger than 750 (750 is set according to my rendering, specific numerical reference rendering), set clientWidth=750 to prevent font-size from exceeding 100px.
            if (clientWidth > _client) {
                clientWidth = _client
            }
            //Set the font-size size of the root element
            docEl.style.fontSize = 100 * (clientWidth / _client) + 'px';
        };
    //Trigger function when screen size changes or screen switching
    win.addEventListener(resizeEvt, recalc, false);
    //Trigger function when document loading is complete
    doc.addEventListener('DOMContentLoaded', recalc, false);
}
//Util.getFontSize(750)
//The way to use it is very simple. For example, on the effect map, there is a picture. The width and height are 100 px.
//750 is the width of the design drawing
//Style writing is
img{
    width:1rem;
    height:1rem;
}
//For example, on devices with a screen width greater than or equal to 750px, 1rem=100px; the image display is 100px in width and height.
//For example, on the iPhone 6 (screen width: 375), 375/750*100=50px; that is, 1rem=50px; the image shows that the width and height are 50px;

5-9ajax

/* Encapsulating ajax functions
 * @param {string}obj.type http Connections, including POST and GET
 * @param {string}obj.url url to send the request
 * @param {boolean}obj.async Is it an asynchronous request, true asynchronous, false asynchronous?
 * @param {object}obj.data Send parameters in object type
 * @param {function}obj.success ajax Send and receive callback functions successfully invoked
 * @param {function}obj.error ajax Callback functions that send or receive failed calls
 */
//  Util.ajax({
//      type:'get',
//      url:'xxx',
//      data:{
//          id:'111'
//      },
//      success:function(res){
//          console.log(res)
//      }
//  })
ajax: function (obj) {
    obj = obj || {};
    obj.type = obj.type.toUpperCase() || 'POST';
    obj.url = obj.url || '';
    obj.async = obj.async || true;
    obj.data = obj.data || null;
    obj.success = obj.success || function () {
        };
    obj.error = obj.error || function () {
        };
    var xmlHttp = null;
    if (XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else {
        xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
    }
    var params = [];
    for (var key in obj.data) {
        params.push(key + '=' + obj.data[key]);
    }
    var postData = params.join('&');
    if (obj.type.toUpperCase() === 'POST') {
        xmlHttp.open(obj.type, obj.url, obj.async);
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
        xmlHttp.send(postData);
    } else if (obj.type.toUpperCase() === 'GET') {
        xmlHttp.open(obj.type, obj.url + '?' + postData, obj.async);
        xmlHttp.send(null);
    }
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            obj.success(xmlHttp.responseText);
        } else {
            obj.error(xmlHttp.responseText);
        }
    };
}

5-10 Picture Lazy Loading

//Use a picture instead of a picture when it is not loaded
aftLoadImg: function (obj, url, errorUrl,cb) {
    var oImg = new Image(), _this = this;
    oImg.src = url;
    oImg.onload = function () {
        obj.src = oImg.src;
        if (cb && _this.istype(cb, 'function')) {
            cb(obj);
        }
    }
    oImg.onerror=function () {
        obj.src=errorUrl;
        if (cb && _this.istype(cb, 'function')) {
            cb(obj);
        }
    }
},
//Picture scrolling lazy loading
//@ className {string} traverses the class name of the picture
//@ Start loading default 0 when num {number} distance
//For example, if a picture is 3000 from the top of the document and the num parameter is 200, then when the page scrolls to 2800, the picture loads. Scroll without passing num parameters. Num defaults to 0. Pages are loaded when they scroll to 3000.
//html code
//<p><img data-src="https://user-gold-cdn.xitu.io/2017/12/7/160319f12631736f" class="load-img" width='528' height='304' /></p>
//<p><img data-src="https://user-gold-cdn.xitu.io/2017/12/7/160319f12631736f" class="load-img" width='528' height='304' /></p>
//<p><img data-src="https://user-gold-cdn.xitu.io/2017/12/7/160319f12631736f" class="load-img" width='528' height='304' /></p>....
//Data-src stores the data of src, assigns the value of data-src to the SRC attribute when it needs to be loaded, and the picture will be loaded.
//For more details, see testLoadImg.html
//window.onload = function() {
//    loadImg('load-img',100);
//    window.onscroll = function() {
//        Util.loadImg('load-img',100);
//        }
//}
loadImg: function (className, num, errorUrl) {
    var _className = className || 'ec-load-img', _num = num || 0, _this = this,_errorUrl=errorUrl||null;
    var oImgLoad = document.getElementsByClassName(_className);
    for (var i = 0, len = oImgLoad.length; i < len; i++) {
        //If the picture has been scrolled to the specified height
        if (document.documentElement.clientHeight + document.documentElement.scrollTop > oImgLoad[i].offsetTop - _num && !oImgLoad[i].isLoad) {
            //Record whether the image has been loaded
            oImgLoad[i].isLoad = true;
            //Set the transition, when the picture comes down, there is a change in the transparency of the picture.
            oImgLoad[i].style.cssText = "transition: ''; opacity: 0;"
            if (oImgLoad[i].dataset) {
                this.aftLoadImg(oImgLoad[i], oImgLoad[i].dataset.src, _errorUrl, function (o) {
                    //Add a timer to ensure that the picture has been loaded, and then clear the class specified by the picture to avoid repeated editing.
                    setTimeout(function () {
                        if (o.isLoad) {
                            _this.removeClass(o, _className);
                            o.style.cssText = "";
                        }
                    }, 1000)
                });
            } else {
                this.aftLoadImg(oImgLoad[i], oImgLoad[i].getAttribute("data-src"), _errorUrl, function (o) {
                    //Add a timer to ensure that the picture has been loaded, and then clear the class specified by the picture to avoid repeated editing.
                    setTimeout(function () {
                        if (o.isLoad) {
                            _this.removeClass(o, _className);
                            o.style.cssText = "";
                        }
                    }, 1000)
                });
            }
            (function (i) {
                setTimeout(function () {
                    oImgLoad[i].style.cssText = "transition:all 1s; opacity: 1;";
                }, 16)
            })(i);
        }
    }
}

5-11 keywords labeled

//When these two functions are mostly used for search, the keywords are highlighted
//Create regular characters
//Util.createKeyExp([Front end, come here])
//result:(Front end | Come over)/g
createKeyExp: function (strArr) {
    var str = "";
    for (var i = 0; i < strArr.length; i++) {
        if (i != strArr.length - 1) {
            str = str + strArr[i] + "|";
        } else {
            str = str + strArr[i];
        }
    }
    return "(" + str + ")";
},
//Keyword tagging (multiple keywords separated by spaces)
//Util.findKey('Waiting for me oaks received from next time you leave Happy and Auspicious to stay in Kaesong Hou','Waiting for Kai','i')
//"< I > Watch </i > I received a message from the next time you leave < I > Kai </i > Happy and auspicious stay in < I > Kai </i > City Marquis"
findKey: function (str, key, el) {
    var arr = null,
        regStr = null,
        content = null,
        Reg = null,
        _el = el || 'span';
    arr = key.split(/\s+/);
    //alert(regStr); //e.g.: (front end | come over)
    regStr = this.createKeyExp(arr);
    content = str;
    //alert(Reg); // e.g.: (Front End | Come over)/g
    Reg = new RegExp(regStr, "g");
    //Filter html tags to replace tags and tag keywords before and after
    content = content.replace(/<\/?[^>]*>/g, '')
    return content.replace(Reg, "<" + _el + ">$1</" + _el + ">");
}

5-12 Data Type Judgment

//Util.istype([],'array')
//true
//Util.istype([])
//'[object Array]'
istype: function (o, type) {
    if (type) {
        var _type = type.toLowerCase();
    }
    switch (_type) {
        case 'string':
            return Object.prototype.toString.call(o) === '[object String]';
        case 'number':
            return Object.prototype.toString.call(o) === '[object Number]';
        case 'boolean':
            return Object.prototype.toString.call(o) === '[object Boolean]';
        case 'undefined':
            return Object.prototype.toString.call(o) === '[object Undefined]';
        case 'null':
            return Object.prototype.toString.call(o) === '[object Null]';
        case 'function':
            return Object.prototype.toString.call(o) === '[object Function]';
        case 'array':
            return Object.prototype.toString.call(o) === '[object Array]';
        case 'object':
            return Object.prototype.toString.call(o) === '[object Object]';
        case 'nan':
            return isNaN(o);
        case 'elements':
            return Object.prototype.toString.call(o).indexOf('HTML') !== -1
        default:
            return Object.prototype.toString.call(o)
    }
}

5-13 Mobile Phone Type Judgment

browserInfo: function (type) {
    switch (type) {
        case 'android':
            return navigator.userAgent.toLowerCase().indexOf('android') !== -1
        case 'iphone':
            return navigator.userAgent.toLowerCase().indexOf('iphone') !== -1
        case 'ipad':
            return navigator.userAgent.toLowerCase().indexOf('ipad') !== -1
        case 'weixin':
            return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
        default:
            return navigator.userAgent.toLowerCase()
    }
}

5-14 function throttling

//Used for high frequency trigger events such as mouse scroll, movement, window size change, etc.
// var count=0;
// function fn1(){
//     count++;
//     console.log(count)
// }
// // Calls that are triggered continuously within 100 ms, and the latter call eliminates the waiting for the former call, but executes at least once every 200 ms
// document.onmousemove=Util.delayFn(fn1,100,200)
delayFn: function (fn, delay, mustDelay) {
    var timer = null;
    var t_start;
    return function () {
        var context = this, args = arguments, t_cur = +new Date();
        //Clean up the last call trigger first (the last call trigger event does not execute)
        clearTimeout(timer);
        //If there is no trigger time, then the current time is the trigger time.
        if (!t_start) {
            t_start = t_cur;
        }
        //If the current time-trigger time is greater than the maximum time interval (mustDelay), trigger a function to run
        if (t_cur - t_start >= mustDelay) {
            fn.apply(context, args);
            t_start = t_cur;
        }
        //Otherwise delayed execution
        else {
            timer = setTimeout(function () {
                fn.apply(context, args);
            }, delay);
        }
    };
}

6. Packaging

There may be some doubts from small partners. It is a bit troublesome to encapsulate and invoke in this way. Why not encapsulate directly on the prototype and make it convenient to invoke. Like the chestnuts below!

String.prototype.trim=function(type){
    switch (type){
        case 1:return this.replace(/\s+/g,"");
        case 2:return this.replace(/(^\s*)|(\s*$)/g, "");
        case 3:return this.replace(/(^\s*)/g, "");
        case 4:return this.replace(/(\s*$)/g, "");
        default:return this;
    }
}
//'  12345 6 8 96  '.trim(1)
//"123456896"
//It is more convenient to call trim ('123456896', 1).
//However, this is not recommended, which pollutes the String of native objects, and the String created by others will be polluted, causing unnecessary overhead.
//What's more, in case the original method is renamed again, the original method will be overwritten.
//String.prototype.substr=function(){console.log('asdasd')}  
//'asdasdwe46546'.substr()
//asdasd 
//What's the function of substr method? You should know, you can go to w3c to see if you don't know.

So the modification of the prototype of native object is not recommended! At least a lot of companies prohibit such operations!

So the recommended encapsulation posture is

var Util={
    trim:function(){..},
    changeCase:function(){..}...
}

7. summary

I encapsulate this by myself, not because I have the habit of making wheels, but because:

1. All of them are commonly used, but there are scattered small examples. There are basically no plug-ins on the Internet.

2. Because there are scattered small instances involving string, array, object and other types, even if plug-ins are found, more than one plug-in is likely to be introduced in the project.

3. It's all simple code, and it's easy to encapsulate. Maintenance is also simple.

Tags: Java JQuery JSON Mobile Android

Posted on Wed, 11 Sep 2019 20:22:50 -0700 by jonoc33