Enrich your JavaScript class library

Source: Internet
Author: User
Tags getdate return tag stringbuffer
enrich your JavaScript class libraryEvery good developer will form its own class library, and as a Java developer, we will also write a bunch of tool classes to simplify our development efforts. But as a full station siege lion, not only to understand the formation of Java class Library, JavaScript class library is equally important. Well, this article does not say much nonsense, the next face of the code provides some very convenient tool classes, or to the JavaScript existing objects extension, such as String extension, Date object extension, array expansion, and so on. Similarly, a StringBuffer object is provided, and the object's usage is basically the same as Java.lang.StringBuffer ...
/** * This file contains some JavaScript classes that simulate Java common classes * This contains a few commonly used classes in the Java.lang,java.util package * * In order to make it easier to manipulate strings, this also gives the string a strong * array, and the date Stringbuffer,list,map,set * * * @author: Luohong * @date: 2015-10-21 13:40 pm * @email 846705189@qq.com/ /======================================== Implement a stringbuffer====================================///** *
	Analog StringBuffer * The use of the process is basically the same as the Java.lang.StringBuffer, but in ToString you can insert the style character, the default separator is ', ' * */function StringBuffer () {  This.strs = [];  Use an array to cache all content if (typeof stringbuffer._initialized = = "undefined") {stringbuffer._initalized = true;
			has been initialized and does not require repeated initialization of 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 | | | = = Undefined | |
'');

}; /** * Function: Remove the trailing space * * * String.prototype.trim = function () {return this.replace (/(^[\t\n\r]+) | (
[\t\n\r]+$)/g, ');

};

/** * Function: Remove the Left space */String.prototype.lTrim = function () {return this.replace (/(^\s*)/g, "");

/** * Function: Remove the right space */String.prototype.rTrim = function () {return this.replace (/(\s*$)/g, ""); /** * Judge whether the end is equal * * @param str * @param iscasesensitive * @returns {Boolean}/String.prototype.endWith = function ( STR, iscasesensitive) {if (str = NULL | | str = = "" | | This.length = 0 | |
	Str.length > This.length) return false;
	var tmp = this.substring (this.length-str.length);
	if (iscasesensitive = = undefined | | iscasesensitive) {return tmp = = str;
	else {return Tmp.tolowercase () = = Str.tolowercase ();

}
}; /** * Determine whether the beginning is equal * * @param str * @param iscasesEnsitive * @returns {Boolean} */String.prototype.startWith = function (str, iscasesensitive) {if (str = NULL | | str = = "" || This.length = 0 | |
	Str.length > This.length) return false;
	var tmp = this.substr (0, str.length);
	if (iscasesensitive = = undefined | | iscasesensitive) {return tmp = = str;
	else {return Tmp.tolowercase () = = Str.tolowercase ();

}
}; /** * to the left of the string to complement the specified number of characters * * @param c * specified character * @param count * The number of times to use: Var str= "999"; Str=str.leftpad ("0", 3);
		STR will output "000999" * @returns */String.prototype.leftPad = function (c, count) {if (!isnan (count)) {var a = "";
		for (var i = This.length i < count; i++) {a = A.concat (c);
		} A = A.concat (this);
	return A;
return null;

}; /** * to the right of the string to complement the specified number of characters * * @param c * specified characters * @param count * The number of times to use: 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;

};
 /** * Encodes HTML characters using: Str=str.htmlencode (); * * @returns/String.prototype.htmlEncode = function () {return this.replace (/&/g, "&"). Replace (/</g, "&L t; ").

Replace (/>/g, ">"). Replace (/\ "/g," ""). Replace (/\ '/g, "");
 /** * Decoding the use of HTML strings: Str=str.htmldecode (); * * @returns/String.prototype.htmlDecode = function () {return this.replace (/\&\;/g, ' \& '). Replace (/\>\;
/g, ' \> '). Replace (/\<\;/g, ' \< '). Replace (/\ "\;/g, ' \"). Replace (/\&\ #39 \;/g, ' \ ');

}; /** * The special characters in JSON are escaped/String.prototype.jsonEscape = function () {return this.replace (/\ "/g," ""). Replace (/\n/g, "&am

P;nuot; ");}; /** * The special characters in JSON are escaped/String.prototype.jsonUnescape = function () {return this.replace (/"/g," \ "). Replace (/&nuo
t;/g, "\ n");

}; /** * String Replacement * * @param s1 * need to replace the character * @pAram S2 * replaced 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}, Sex: {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 ==============================================///** *  Move the specified object in the array/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] * methods to determine whether objects are the same (optional arguments, the default implementation is depth matching two objects are the same), Example: function (x,y) {if x.id===y.i
 D) return * TRUE;}
	*/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]);
			else {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 to 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.getmonth () + 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 Date ======================================== ==//
The above code, which provides some common methods in Java, is the development of JavaScript and Java development is very similar, 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 ();
Date.current ();
Date.currentdate ();

var str = "";
Str.isempty ();            True
str.startwith (' aaaa ');    False

var 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 through the prototype object to extend the JavaScript base object, below provides a date tool class, for the operation date related operations: Compare time, get the current month's first and last day, format date, etc.
/** * Date Tool class * Currently only formatted function * * @author Shen Shaoqin * @date 2016-04-20 11:19/var dateutils = {/** * * @par AM {[Date]} date [DateTime object], if no, then use new Date (). 
     This is the computer date * @param {[Date]} pattern [format rule], 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": date.getdate (),//day "H": date.gethours (),//Hour "M": date.getminutes (),//min "S": Date.getseconds (),//sec "Q": Math.floor (Date.getmonth () + 3)/3),//Quarter
            S ": date.getmilliseconds ()//MS};
                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_ .
                Default_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 = new date ();
        var value = Date.getday ()-1;
        var result = ' Week ';
                Switch (value) {Case 0:result = "one";
            Break
                Case 1:result + = "two";
            Break
                Case 2:result + = "three";
            Break
                Case 3:result + = "four";
            Break
                Case 4:result + = "Five";
            Break
                Case 5:result + = "Six";
            Break
                Case 6:result = "Day";
        Break
    return result; }, getenglishweeks:function (date = {if (date = = NULL | | = Date = = undefined) {date = new Da
        Te ();
        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 time difference * @param starttime start * @param endtime End time * @param difftype Variance Type, sec Ond,minute,hour,day * @return return time difference, integer type * * Use example: * var result = Dateutils.getdatediff ("2010-02-26 16
     : 00:00 "," 2011-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) {//Convert XXXX-XX-XX time format to XXXX/XX/XX format Startti me = StartTime. replace (/\-/g, "/");
        
        Endtime = Endtime.replace (/\-/g, "/");
        Converts the calculated 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));
        /** * Converts seconds to: X hour Z min y sec * @param {int} seconds sec/tochinesetime:function (seconds) {
        var hour = "";
        var minute = parseint (SECONDS/60); seconds = parseint (seconds% 60);
            if (minute >=) {hour = parseint (MINUTE/60);
        minute = parseint (minute% 60);
        var result = seconds + "seconds";
        if (minute) {result = minute + "min" + result;
        } if (hour) {result = Hour + "hour" + result;
    return result; /** * Get the current date of the days before the date * @param n interval days * @param startdate start date, default for the day * Use example: dateutils.getbefor EDate (5), Dateutils.getbeforedate (5, ' 2016-05-06 ') * return format such as: Yyyy-mm-dd/Getbeforedate:function (n, Startdat
        
        e) {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 day after date of the current date * @param n interval days * @param startdate start date, default for the day * Use example: dateutils.getafterdate
        (5), Dateutils.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 ();
		Date.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 year/day mode Default_date_time_pattern: "Yyyy-mm-dd H  H:mm:ss ",//default full mode Default_time_pattern:" HH:mm:ss ",///default time in seconds mode Default_mon_day_hou_min_pattern:" Mm-dd hh:mm ", The default month-day time mode Default_mon_day_pattern: "Mm-dd",//Default month-day mode default_hou_min_pattern: "hh:mm"//Default time-division mode};

SummaryWith the example above, we can encapsulate some common components of JavaScript, form our own development class library, later develop new projects, direct these JS class library moved past, can greatly simplify our search for code time, do not have to rely on too much Google, And then copy the process.
Related Article

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.