JS commonly used in strings, arrays, function extensions

Source: Internet
Author: User
Tags hasownproperty

1. String extension:

;(function () {var method, Stringextends = {/** * Delete whitespace at start and end of String * @returns {string} */        Strip:function () {return this.replace (/^\s+|\s+$/gm, ');  },/** * Delete the left blank of the string * @returns {string} */Stripleft:function () {return        This.replace (/^\s+/, ");  },/** * Remove the whitespace to the right of the character * @returns {string} */Stripright:function () {return         This.replace (/\s+$/, ')},/** * Determines whether a string is empty, or returns True when the empty string or contains only white space characters * @returns {Boolean}        */Blank:function () {return This.strip (). length = = 0;        },/** * Converts the property name in CSS to the style name in JS, Background-color, BackgroundColor * @returns {string} */ Camelize:function () {return this.replace (/(\-\w)/g, function (match) {return match.slice            (1). toUpperCase (); })        },        /**         *Capitalize the first letter of a string, other characters lowercase * @returns {string} */Capitalize:function () {return This.strip ().            Replace (/^ (\w{1}) (. *)/g, function (match, G1, G2) {return g1.touppercase () + g2.tolowercase ();        }); },/** * Converts an underscore in a string to an underscore * @returns {string} */Dasherize:function () {R        Eturn this.replace (/\_/g, '-'); },/** * detects if string is empty string * @returns {Boolean} */Empty:function () {return th           Is.length = = 0; /* ". empty (); -True '. Empty ();//-> false*/},/** * detects if a string ends with a specific string * @param {St Ring} Target * @returns {boolean} */Endswith:function (target) {return (new RegExp (tar            get+ ' $ ')). Test (this);        Return This.slice (-target.length) = = = Target; },/** * detects if a string starts with a specific string * @param {string} target * @retUrns {Boolean} */Startswith:function (target) {return (new RegExp (' ^ ' +target)). Test (this);        },/** * detects if a string contains a specific String * @param {string} target * @returns {boolean} */        Contains:function (target) {return This.indexof (target)!==-1; },/** * * @param {number} N-Times to repeat * @returns {string} */Times:function            (n) {//return new Array (n+1). Join (this); /*return [].join.call ({length:n + 1}, this); *//using binary var ret, flag = f            Alse, str = this.tostring ();            if (n = = 0) return ';            if (n = = 1) return str;                if (n% 2) {//odd n = n-1;            Flag = true;            } ret = Str.times (N/2); Return flag?        (ret + ret + str): (ret + ret); },/** * onThe special characters in the string are escaped, avoiding XSS */escapehtml:function () {//escaped characters are values that can be set directly to innerHTML. Replace (/&/g, ' &amp; ')                    This replace () call must be written in front of all special character escapes, otherwise the & symbol will be transferred once again return This.replace (/&/g, ' &amp; ')                    . replace (/\</g, ' &lt; ')                    . replace (/\>/g, ' &gt; ')                    . replace (/\ '/g, ' & #39; ')            . replace (/\ "/g, ' &quot; ');            /*var Strarr = This.split (");                for (var pos = 0, L = strarr.length, tmp; POS < L; pos++) {tmp = Strarr[pos];                        Switch (TMP) {case ' < ': Replacearr (Strarr, POS, ' &lt; ');                    Break                        Case ' > ': Replacearr (Strarr, POS, ' &gt; ');                    Break                        Case ' \ ': Replacearr (Strarr, POS, ' & #39; ');         Break           Case ' \ ': Replacearr (Strarr, POS, ' &quot; ');                    Break                        Case ' & ': Replacearr (Strarr, POS, ' &amp; ');                    Break                Default:;            }} return Strarr.join (");            function Replacearr (arr, pos, item) {return Arr.splice (POS, 1, item); }*/},/** * Reverses the literal string */Unescapehtml:function () {return This.replace (/                &amp;/, ' & '). Replace (/&lt;/g, ' < '). Replace (/&gt;/g, ' > ') . replace (/& #39;/g, ' \ '). Replace (/&quot;/g, ' \ '). Replace (/&# (\d+)/g, func                tion ($, $) {return String.formcharcode (parseint ($ 10));        }); },/** * Gets the inverse of the string * @returns {string} */Reverse:function () {return (this.tostring ()). Split ("). Reverse (). Join ('); },/** * Intercepts the string and can specify a fill suffix * @param {number} [length = 30]-truncate length, default to 30 characters * @param {string}            [suffix = ' ... ']-populate suffix, default to ' ... ' * @returns {string} */truncate:function (length, suffix) {            var ret = this.tostring (); Length = Length | |            30; suffix = suffix | |            ‘...‘;            If the string is not less than length, return the string if (Ret.length < length) {return ret;        } return Ret.slice (0, length-suffix.length) + suffix; },/** * Remove HTML tag from String * @returns {string} */Striptags:function () {RET Urn This.replace (/(\<\w+\s?. *?\>) | (\<\/\w+\s?).            *?\>)/g, function () {return ';        }); },/** * Remove the script from the string * @returns {string} */Stripscripts:function () {Retu RN ThiS.replace (/\<script\>.*?\<\/script\>/, function () {return ';    })        }    }; For (method in Stringextends) {Stringextends.hasownproperty (method) && typeof String.prototype[metho    D]!== ' function ' && (string.prototype[method] = Stringextends[method]); }})();

2. Array expansion

;(function () {var method, Arrayextends = {/** * Increments the iteration method in the array ES5: ForEach, map, filter, every, some         * Standard Specification: Each method receives two parameters, the back harmonic (optional) to run on each item, the context of the function when the callback is run * The parameters of the callback function will contain three parameters: the value of the array item, the position, and the group itself. *//** * Each item of the array executes a callback, and this method does not return a value */foreach:function (FN, CTX) {for (var i = 0, L = this.length; I &lt ; L            i++) {fn.call (CTX | | null, THIS[I], I, this);  }},/** * runs a callback function for each item of the array, returning the arrays consisting of the results of the callback function */map:function (FN, ctx) {var ret            = [];            for (var i = 0, L = this.length; i < L; i++) {Ret.push (Fn.call (CTX | | null, THIS[I], I, this));        } return ret; },/** * array per-item run callback function, returns a callback function that returns a value of True consisting of a */Filter:function (FN, ctx) {var ret            = [];       for (var i = 0, L = this.length; i < L; i++) {Fn.call (CTX | | null, THIS[I], I, this) &&         Ret.push (This[i]);        } return ret; },/** * Runs the callback function for each item of the array, and returns True if all the callback functions return True */Every:function (FN, CTX) {for ( var i = 0, L = this.length; I < L; i++) {!!                Fn.call (CTX | | null, THIS[I], I, this) = = = FALSE;            return false;        } return true; },/** * runs a callback function for each item of an array, returns true if there is a callback function (FN, CTX) {for (VA R i = 0, L = this.length; I < L; i++) {!!                Fn.call (CTX | | null, THIS[I], I, this) = = = true;            return true;        } return false;         },/** * Runs the callback function from left to right (smooth) for each item in the array (starting with the second entry, which is subscript 1). * The callback function contains four parameters prev (the return value of the last callback), cur (the current array item), index (the current array entry), self (the array itself) * @param {Function} callback * @retur       NS {*} */Reduce:function (callback) {var i = 1,//starting from the second element of the array L = this.length,         Callbackret = This[0];            for (; I < L; ++i) {Callbackret = Callback.call (null, Callbackret, this[i], I, this);        } return Callbackret;         },/** * Runs the callback function from right to left (in reverse order) for each item in the array (starting from the penultimate item, which is subscript arr.length-2). * The callback function contains four parameters prev (the return value of the last callback), cur (the current array item), index (the current array entry), self (the array itself) * @param {Function} callback * @retur NS {*} */Reduceright:function (callback) {var L = this.length, i = l-2,//from array The penultimate element begins Callbackret = This[l-1]; The callback initial value is the value of the last element of the array for (; I >= 0; i) {callbackret = Callback.call (null, Callbackret, this[i            ], I, this);        } return Callbackret;         },/** * Returns the position where the target value first appears in the array, and the search is left-to-right. * Returns 1 if the target value does not exist in the array. You can specify a search start location.         The default is 0 * @param {number} target * @param {number} [start = 0]-start defaults to 0 * @returns {number} */indexOf: function (target, start) {var L = this.length, start = ~~start;//can specify a search starting position. The default is 0.            Start does not pass, default is undefined,~~undefined, 0 if (Start < 0) Start = 0;//If the specified search location is less than 0, set its start search position to 0            for (; start < L; ++start) {if (this[start] = = = target) return start;        } return-1; },/** * Returns the position of the target value in the array. Search from right to left * returns 1 if the target value does not exist in the array. You can specify a search start location.  Default array length * @param {number} target * @param {number} [start = Arr.length]-Start search location default array length * @returns            {Number} */Lastindexof:function (target, start) {var L = this.length;            if (start = = = void 0) start = this.length;            else if (Start < 0) start = 0;            for (; start >= 0;--start) {if (this[start] = = = target) return start;        } return-1; },        /**        * Array de-weight * @returns {Array} */Unique:function () {var i = 0, J, l            = This.length;                        for (; I < L; ++i) {for (j = i+1; J < L, + j) {if (this[i] = = = This[j]) {        This.splice (J, 1);//Remove the array entry for position J}}} return this;         },/** * for arrays of a single type, you can use this method to go heavy. * But this type of array: [' FF ', 1, ' 1 '] will go back to fail * @returns {array} */Enhanceunique:function () {var ret            = [], Tempmap = {}, temp, i = 0, L = this.length, undef = void 0;                for (; I < L; ++i) {temp = this[i];                    if (tempmap[temp] = = = undef) {Ret.push (temp);                Tempmap[temp] = true;        }} return ret; },/** * Removes the target element from the array * @param value * @returns {array} */Without:funCtion () {var args = [].slice.call (arguments). Unique (), i = 0, L = this.length, J            = 0, k = args.length;                        for (; M < L; ++i) {for (; J < K; ++j) {if (this[i] = = = Args[j]) {                    This.splice (i, 1);        }} j = 0;//J to 0 for the next loop} return this; },/** * recursively flattens the array * @returns {array} */Flatten:function () {var ret = [            ], i = 0, L = this.length, tmp, tostring = ({}). tostring;                for (; I < L; ++i) {tmp = this[i];                if (Tostring.call (tmp) = = = ' [object Array] ') {ret = Ret.concat (Tmp.flatten ());                } else {Ret.push (TMP);        }} return ret;        },/** * Randomly returns an item of the array * @returns {*} */Random:function (n) {    Math.floor (): Rounding down. Math.floor (1.8), 1//math.ceil (): Rounding up. Math.ceil (1.1), 2//v = Math.random () * N: Generates a number of 0 < V < NV//V2 = Math.floor (Math.rando        M () * N): V2 is an integer greater than or equal to 0, less than N, return This[math.floor (Math.random () * n | | this.length)]; },/** * Deletes the item at the specified position in the array * @returns {array} */Removeat:function (POS) {this.            Splice (POS, 1);        return this;            },/** * detects if the array contains target values * @returns {Boolean} */Contains:function (target) {            Return This.some (function (e, I, self) {return E = = = target;        }); },//array of intersection, and, difference set/** * Returns an array of arrays with the intersection of the target array * @returns {array | | null} */INTERSEC            T:function (target) {var Originalarr = This.unique (), target = Target.unique (); Return Originalarr.filter (function (e, I, self) {foR (var i = 0, L = target.length; i < L; ++i) {if (E = = = Target[i]) {return T                    Rue            }} return false;        });            },/** * Returns an array of arrays with the set of the target array * @returns {array | | null} */Union:function (target) {        return This.concat (target). Unique ();            },/** * Returns an array of array with the difference set of the target array * @returns {array | | null} */Diff:function (target) {            var Originalarr = This.unique (), target = Target.unique ();                    Return Originalarr.filter (function (e, I, self) {for (var i = 0, L = target.length; i < L; ++i) {                    if (e = = = Target[i]) {return false;            }} return true;        });     },/** * empties the array and returns a reference to this array * @returns {array} */Clear:function () {       this.length = 0;        return this;        }, Clone:function () {return [].concat (this);            },/** * Removes undefined from the array, null * @returns {array} */Compact:function () {                    for (var i = 0, L = this.length; i < L; i++) {if (this[i] = = NULL)//delete element of this position            This.splice (i, 1);        } return this;        },/** * Returns the first item of the array * @returns {*} */First:function () {return this[0]; },/** * Returns the last item of the array * @returns {*} */Last:function () {return this[        THIS.LENGTH-1]; },/** * Returns the size of the array, that is, the array length * @returns {Number} */Size:function () {return T        His.length;    }    }; For (method in Arrayextends) {Arrayextends.hasownproperty (method) && typeof Array.prototype[method] !== ' functIon ' && (Array.prototype[method] = Arrayextends[method]); }})();

3. function extension

The;(function () {var method, Functionextends = {/** * * Returns a function: * 1. This function is scoped, which is the this value *         2. If you run bind () with other parameters that are passed outside this, the function will also contain these parameters.        * These parameters are combined with the parameters returned by the bind () to form the parameters of the returned function (simultaneous): {*} othis-the scope to bind to the function * @returns {function} */ Bind:function (othis) {var _slice = [].slice, args = _slice.call (arguments, 1),//Run bind ( ) method = this;//The function to be actually run return functions () {return method.apply (oTh            IS, Args.concat (_slice.call (arguments)));         }},/** * Function curry is a processing of parameters, which gives more flexibility in controlling parameters.         * The key point is when the return function continues to increment the parameter and when to execute the function to return the result.         * To solve the above problem you can introduce a variable at curry and manually set the minimum number of required parameters. * @param {Number} [Minargsnumber = 0]-no parameters required by default * @returns {*} */curry:function (Minargsnumber)  {var _slice = [].slice, Closureargs = _slice.call (arguments, 1), method = this,              Totalargs; Minargsnumber = arguments.length?            Arguments[0]: 0; Minargsnumber = typeof Minargsnumber = = = ' Number '?            minargsnumber:0; return function inner () {///whether the function is executed or continues to wait for the parameter to be determined by minargsnumber Totalargs = typeof Totalargs = =                    = ' undefined '?                Closureargs.concat (_slice.call (arguments)): Totalargs.concat (_slice.call (arguments)); if (totalargs.length >= minargsnumber) {//Execute function return method.apply (this, totalarg                s);                } else {//continue to return function to receive the parameter return inner; }}},/** * Returns the parameter moniker string of the function as an array. Empty array returned when no parameters * @returns {array} */Argumentnames:function () {var ret, met                Hodcode = This.tostring (); Methodcode.replace (/\ (. *?) \) The code inside the//*GM function may also have (ABC) string */, function (match, G1){var argstr = g1.replace (/\s/g, '); ret = argstr.length?                Argstr.split (', '): [];            });        return ret;                },/** * settimeout's lazy wording */delay:function (delay) {var _slice = [].slice,            method = this, Closureargs = _slice.call (arguments, 1);            SetTimeout (function () {method.apply (this, Closureargs.concat (_slice.call (arguments)));        }, delay);    }    }; For (method in Functionextends) {Functionextends.hasownproperty (method) && typeof Function.prototype    [Method]!== ' function ' && (function.prototype[method] = Functionextends[method]); }})();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.