Enrich your JavaScript class library

Source: Internet
Author: User
Tags return tag

Enrich your JavaScript library each good developer will form its own class library, and as a Java developer, we will also write a bunch of tools to simplify our development efforts. But as a full-station siege Lion, not just understand the formation of Java class Library, JavaScript class library is equally important. Well, this article does not say much nonsense, the following code provides some very convenient tool classes, or is the extension of JavaScript already have objects, such as the extension of the string, the extension of the Date object, the expansion of the array, and so on. Similarly, a StringBuffer object is provided, and the use of the object is basically the same as Java.lang.StringBuffer ...
/** * This file contains some JavaScript classes that mimic Java common classes * This includes some of the common classes in the Java.lang,java.util package * * In order to make it easier to manipulate strings, the string is also given a strong * array, The date has also been enhanced * * For example: Stringbuffer,list,map,set * @author: Luohong * @date: 2015-10-21 13:40 pm * @email [email protected] *///======================================== implements a stringbuffer====================================///** * Simulation StringBuffer * Using the process is basically the same as Java.lang.StringBuffer, but in ToString you can insert a style character, the default delimiter is ', ' * */function StringBuffer () {  This.strs = [];  Use an array to cache all the contents if (typeof stringbuffer._initialized = = "undefined") {stringbuffer._initalized = true; Initialized StringBuffer.prototype.append = function (str) {this.strs.push (str); return this;}; StringBuffer.prototype.toString = function (seperator) {if (!seperator) {seperator = "";} Return This.strs.join (Seperator);}} ======================================== implements a stringbuffer====================================////============= ======================= Enhanced String =============================================///** * Determines whether the string is empty. * * @returns{Boolean} */string.prototype.isempty = function () {return (this = NULL | | this = undefined | | this = = ");};/ * * Function: Remove the trailing space */string.prototype.trim = function () {return this.replace (/(^[\t\n\r]+) | ( [\t\n\r]+$]/g, ');};/ * * Function: Remove left space */string.prototype.ltrim = function () {return this.replace (/(^\s*)/g, "");};/ * * Function: Remove right space */string.prototype.rtrim = function () {return this.replace (/(\s*$)/g, "");};/ * * Determine if the end is equal * * @param str * @param iscasesensitive * @returns {Boolean} */string.prototype.endwith = function (str, IsC asesensitive) {if (str = = NULL | | str = = "" | | This.length = = 0| | Str.length > This.length) return false;var tmp = this.substring (this.length-str.length); if (iscasesensitive = = Undefi Ned | | iscasesensitive) {return tmp = = str;} else {return tmp.tolowercase () = = Str.tolowercase ();}};/ * * Determine if the start is equal * * @param str * @param iscasesensitive * @returns {Boolean} */string.prototype.startwith = function (str, I scasesensitive) {if (str = = NULL | | str = = "" | | This.length= = 0| | Str.length > This.length) return false;var tmp = THIS.SUBSTR (0, str.length); if (iscasesensitive = = Undefined | | iscasese nsitive) {return tmp = = str;} else {return tmp.tolowercase () = = Str.tolowercase ();}};/ * * to the left of the string to be filled with a specified number of characters * * @param c * specified characters * @param count * The number of times used: Var str= "999"; Str=str.leftpad ("0", 3); STR outputs "000999" * @returns */string.prototype.leftpad = function (c, count) {if (!isnan (count)) {var a = ""; for (var i = t His.length; I < count; i++) {a = A.concat (c);} A = A.concat (this); return A;} Return null;};/ * * The specified number of characters are padded to the right of the string * * @param c * specified characters * @param count * The number of times to be used: var str= "999"; Str=str.rightpad ("0", 3); STR will output * "999000" * @returns */string.prototype.rightpad = function (c, count) {if (!isnan (count)) {var A = this ; for (var i = this.length; i < count; i++) {a = A.concat (c);} return A;} Return null;};/ * * Encode HTML characters using: Str=str.htmlencode (); * * @returns */string.prototype.htmlencode = FuNction () {return this.replace (/&/g, "&"). Replace (/</g, "<"). Replace (/>/g, ">"). Replace (/\ "/g," " "). Replace (/\ '/g," ' ");};/ * * For HTML string decoding usage: Str=str.htmldecode (); * * @returns */string.prototype.htmldecode = function () {return this.replace (/\&\;/g, ' \& '). Replace (/\>\;/g , ' \> '). Replace (/\<\;/g, ' \< '). Replace (/\ "\;/g, ' \ '). Replace (/\&\ #39 \;/g, ' \ ');};/ * * to escape special characters in json */string.prototype.jsonescape = function () {return this.replace (/\ "/g," ""). Replace (/\n/g, "& Nuot; "};/"); * * to escape special characters in json */string.prototype.jsonunescape = function () {return this.replace (/"/g," \ ""). Replace (/&nuot ;/g, "\ n");};/ * * String Substitution * * @param s1 * characters that need to be replaced * @param s2 * Replace characters. * @returns */string.prototype.replaceall = function (S1, S2) {return this.replace (new RegExp (S1, "GM"), S2);};/ * * Get URL parameter * * @returns {object} */string.prototype.getargs = function () {var args = {};if (This.indexof ("?") >-1) {var argstr = This.split ("?") [1], argary = Argstr.split ("&"); for (var i = 0, c; c = argary[i++];)  {var pos = c.indexof ("="); if (pos = =-1) Continue;var argname = c.substring (0, pos), Argval = c.substring (pos + 1); Argval = decodeURIComponent (Argval); Args[argname] = Argval;}} Return args;};/ * * var Str=string.format ("name: {0}, Gender: {1}", "Ray", "male"); alert (str); * * @returns */string.prototype.format = function () {var template = Arguments[0];var args = Arguments;var str = template. Replace (/\{(\d+) \}/g, function (M, i) {var k = parseint (i) + 1;return args[k];}); Return str;};/ /==================================== Enhanced String =============================================////==================== ================ Enhanced Array ==============================================///** * Removes the specified object in the divisor group */array.prototype.remove = Function (val) {for (var i = 0; i < this.length; i++) {if (this[i] = = = val) {This.splice (I, 1); i--;}} Return this;};/ /insert Element Array.prototype.insert = function (index, item) {this.splice (index, 0, item); return this;};/  * * Remove Duplicates in array ** @function [Method] * Determines whether the object is the same (optional parameter, the default implementation is the depth of the match two objects are the same), Example: function (x, y) {if (x.id===y.id) return * TR UE;} */array.prototype.unique = function (method) {if (!angular.isarray (this)) return This;var Sameobj = Method | | Function (A, B) {var tag = true;for (var x in a) {if (!b[x]) return False;if (typeof (a[x]) = = = ' object ') {tag = Sameobj (A[x], b[x]);} E LSE {if (A[X]!== b[x]) return false;}} return tag;} var flag, that = This.slice (0), this.length = 0;for (var i = 0; i < that.length; i++) {var x = That[i];flag = True;for (var j = 0; J < This.length; J + +) {y = this[j];if (sameobj (x, y)) {flag = False;break;}} if (flag) this[this.length] = x;} return this;} ==================================== Enhanced Array ==============================================////=================== ================== enhanced date, gets xxxx-mm-yy hh:mm:ss format Date ==========================================///** * Returns the current time, The format is as follows: 2016-06-06 12:12:12 */date.prototype.current = function () {var year = this.getfullyear (); Var month= (This.getmonth () + 1) < 10? (0 + "" + (This.getmonth () + 1): (This.getdate () + 1); var date = This.getdate () < 10? (0 + "" + This.getdate ()): This.getdate (); var hours = This.gethours () < 10? (0 + "" + This.gethours ()): This.gethours (); var minutes = This.getminutes () < 10? (0 + "" + This.getminutes ()): This.getminutes (); var seconds = This.getseconds () < 10? (0 + "" + This.getseconds ()): This.getseconds (); return year + "-" + month + "-" + date + "+ Hours +": "+ minutes +": "+ seconds;};/ * * Returns the current date in the following format: 2016-06-06 */date.prototype.currentdate = function () {var year = this.getfullyear (); var month = This.getm Onth () + 1;if (Month <) {month = "0" + month;} var date = This.getdate () < 10? (0 + "" + This.getdate ()): This.getdate (); return year + "-" + month + "-" + date;};/ /===================================== enhanced date to get XXXX-MM-YY hh:mm:ss format dates ========================================= =//
The above code, which provides some common methods in Java, is the development of JavaScript is very similar to Java development, hey, JavaScript can write like Java 6. Like what
var sb = new StringBuffer (); Sb.append (' Hello '). Append (new Date (). GetTime ()). append (); var date = new Date ();d ate.current ();d ate.currentdate (); var str = ""; Str.isempty ()            ; Truestr.startwith (' aaaa ');    Falsevar array = [1,2,2,3];    [1,2,3]array.<span style= "font-family:arial, Helvetica, Sans-serif;" >unique</span> ();
Of course, the above code, we are directly extending the JavaScript base object through the prototype object, the following provides a date tool class for operation date related actions: Compare time, get the first and last day of the current month, format date, etc.
/** * Date Tool class * Currently only features formatted * * @author Shen Shaoqin * @date 2016-04-20 11:19 */var dateutils = {/** * * @param {[date ]} date [Date Object], if no, then use new Date ().     That's current computer date * @param {[Date]} pattern [formatting rules], if no, then use Dateutils.default_date_time_pattern         * @return {[string]} [formatted date string] */format:function (date/*optional*/, pattern/*optional*/) { Function deal (date, format) {var map = {"M": Date.getmonth () + 1,//month "D": Da Te.getdate (),//day "H": date.gethours (),//Hour "M": date.getminutes (),//min " S ": Date.getseconds (),//sec" Q ": Math.floor ((Date.getmonth () + 3)/3),//Quarterly" S ": Date.getm            Illiseconds ()//msec};                Format = Format.replace (/([YMDHMSQS]) +/g, function (all, t) {var v = map[t];     if (v!== undefined) {if (All.length > 1) {                   v = ' 0 ' + V;                    v = v.substr (v.length-2);                } return v;                } else if (t = = = ' Y ') {return (Date.getfullyear () + "). substr (4-all.length);            } return all;            });        return format; } switch (arguments.length) {case 0:return deal (new Date (), Dateutils._cons_.            Default_date_time_pattern); Case 1:if (Arguments[0] instanceof Date) {return deal (Arguments[0], DATEUTILS._CONS_.D                Efault_date_time_pattern); } else {return deal (dateutils._cons_.                Default_date_time_pattern, Arguments[0]);        } Case 2:return Deal (Arguments[0], arguments[1]); }}, Getchineseweeks:function (date) {if (date = = = NULL | | date = = = undefined) {date = NE        W Date ();       } var value = Date.getday ()-1;        var result = ' Week ';                Switch (value) {case 0:result + = "one";            Break                Case 1:result + = "II";            Break                Case 2:result + = "three";            Break                Case 3:result + = "four";            Break                Case 4:result + = "Five";            Break                Case 5:result + = "VI";            Break                Case 6:result + = "Day";        Break    } return result; }, Getenglishweeks:function (date) {if (date = = = NULL | | date = = = undefined) {date = new date ()        ;        } var value = Date.getday ()-1;            Switch (value) {case 0:return "Monday";            Case 1:return "Tuesday";            Case 2:return "Wensday"; Case 3:return"Thursday";            Case 4:return "Friday";            Case 5:return "Saturday";        Case 6:return "Sunday"; }},/** * Calculates the time difference * @param startTime start times * @param endTime end time * @param difftype difference type, second,min Ute,hour,day * @return return time difference, integer type * * Use example: * var result = Dateutils.getdatediff ("2010-02-26 16:00:00", "2     011-07-02 21:48:40 "," second ");     * var result = Dateutils.getdatediff ("2010-02-26 16:00:00", "2011-07-02 21:48:40", "minute");     * var result = Dateutils.getdatediff ("2010-02-26 16:00:00", "2011-07-02 21:48:40", "hour");     * var result = Dateutils.getdatediff ("2010-02-26 16:00:00", "2011-07-02 21:48:40", "Day"); */Getdatediff:function (startTime, EndTime, Difftype) {//XXXX-XX-XX time format, convert to XXXX/XX/XX format startTime        = Starttime.replace (/\-/g, "/");                EndTime = Endtime.replace (/\-/g, "/"); Convert the computed interval class character to lowercase difftype = difftyPe.tolowercase ();      var stime = new Date (startTime);  Start time var etime = new Date (endTime);        End time var divnum = 1;                Switch (difftype) {case "second": Divnum = 1000;            Break                Case "Minute": divnum = 1000 * 60;            Break                Case "Hour": divnum = 1000 * 3600;            Break                Case ' Day ': divnum = 1000 * 3600 * 24;            Break        Default:break;    } return parseint ((Etime.gettime ()-stime.gettime ())/parseint (divnum)); },/** * format seconds: x hours z minutes y seconds * @param {int} seconds sec */tochinesetime:function (seconds) {var hou        r = "";        var minute = parseint (SECONDS/60);        seconds = parseint (seconds% 60);            if (minute >=) {hour = parseint (MINUTE/60);        minute = parseint (minute% 60); } var result = seconds + "SEC";        if (minute) {result = minute + "min" + result;        } if (hour) {result = Hour + "hour" + result;    } return result; },/** * Gets the date of the previous day of the current date * @param n interval days * @param startdate start date, the default is the day * Use example: Dateutils.getbeforedate (        5), Dateutils.getbeforedate (5, ' 2016-05-06 ') * return format such as: YYYY-MM-DD */getbeforedate:function (n, StartDate) {                var n = n;        var d = null;        if (!startdate) {d = new Date ();            }else{var STRs = startdate.split ('-');            D = new Date ();            D.setyear (Strs[0]);            D.setmonth (Strs[1]-1);        D.setdate (strs[2]);        } var year = D.getfullyear ();        var mon=d.getmonth () +1;        var day=d.getdate ();        D.settime (D.gettime ()-N * 1000 * 60 * 60 * 24);        Year = D.getfullyear ();        Mon = D.getmonth () + 1;        Day = D.getdate (); s = year+ "-" + (mon<10? (' 0 ' +mon): Mon) + "-" + (day<10? ('0 ' +day):d ay);    return s; },/** * Gets the date after the current date * @param n interval days * @param startdate start date, default to day * Use Example: Dateutils.getafterdate (5), D  Ateutils.getafterdate (5, ' 2016-05-06 ') * return format such as: YYYY-MM-DD */getafterdate:function (n, startdate) {var n                = N;        var d = null;        if (!startdate) {d = new Date ();            }else{var STRs = startdate.split ('-');            D = new Date ();            D.setyear (Strs[0]);            D.setmonth (Strs[1]-1);        D.setdate (strs[2]);  } d.settime (D.gettime () + n * 1000 * 60 * 60 * 24);        Update Time year = D.getfullyear ();        Mon = D.getmonth () + 1;        Day = D.getdate (); s = year+ "-" + (mon<10? (' 0 ' +mon): Mon) + "-" + (day<10? ('        0 ' +day):d ay);    return s; },/** * Gets the first day of the current month * @returns {date} */Getcurrentmonthfirst:function () {var date=new Date ();d ate.setdate (1); return date;},/** * Gets the last day of the current month * @returns {date} */getcurrentmonthlast: function () {var date=new date (), Var currentmonth=date.getmonth (), var nextmonth=++currentmonth;var nextmonthfirstday =new Date (Date.getfullyear (), nextmonth,1), var oneday=1000*60*60*24;return new Date (Nextmonthfirstday-oneday);}} Dateutils._cons_ = {default_date_pattern: "YYYY-MM-DD",//default month and day mode Default_date_time_pattern: "Yyyy-mm-dd HH:mm:ss ",//default full mode Default_time_pattern:" HH:mm:ss ",//default time Division seconds Mode Default_mon_day_hou_min_pattern:" Mm-dd hh:mm ",//default month Day Time Division Mode Default_mon_day_pattern: "Mm-dd",//Default month-day mode default_hou_min_pattern: "hh:mm"//Default time division mode};

With the above example, we can encapsulate some of the common JavaScript components to form our own development class library, and then develop new projects, directly to the JS library to move past, can greatly simplify our search for code time, do not have to rely on too much Google, Then copy the process.

Enrich your JavaScript class library

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.