JavaScript 日期格式v1.0

/*
**************************************
* Date.format Function v1.0          *
* Autor: Carlos R. L. Rodrigues      *
**************************************
*/
Date.prototype.format = function(m, r){
    var d = this, a, fix = function(n, c){return (n = n + "").length < c ? new Array(++c - n.length).join("0") + n : n};
    var r = r || {}, f = {j: function(){return d.getDate()}, w: function(){return d.getDay()},
        y: function(){return (d.getFullYear() + "").slice(2)}, Y: function(){return d.getFullYear()},
        n: function(){return d.getMonth() + 1}, m: function(){return fix(f.n(), 2)},
        g: function(){return d.getHours() % 12 || 12}, G: function(){return d.getHours()},
        H: function(){return fix(d.getHours(), 2)}, h: function(){return fix(f.g(), 2)},
        d: function(){return fix(f.j(), 2)}, N: function(){return f.w() + 1},
        i: function(){return fix(d.getMinutes(), 2)}, s: function(){return fix(d.getSeconds(), 2)},
        ms: function(){return fix(d.getMilliseconds(), 3)}, a: function(){return d.getHours() > 11 ? "pm" : "am"},
        A: function(){return f.a().toUpperCase()}, O: function(){return d.getTimezoneOffset() / 60},
        z: function(){return (d - new Date(d.getFullYear() + "/1/1")) / 864e5 >> 0},
        L: function(){var y = f.Y(); return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0},
        t: function(){var n; return (n = d.getMonth() + 1) == 2 ? 28 + f.L() : n & 1 && n < 8 || !(n & 1) && n > 7 ? 31 : 30},
        W: function(){
            var a = f.z(), b = 364 + f.L() - a, nd = (new Date(d.getFullYear() + "/1/1").getDay() || 7) - 1;
            return (b <= 2 && ((d.getDay() || 7) - 1) <= 2 - b) ? 1 :
                (a <= 2 && nd >= 4 && a >= (6 - nd)) ? new Date(d.getFullYear() - 1 + "/12/31").format("%W%") :
                (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
        }
    }
    return m.replace(/%(.*?)%/g, function(t, s){
        return r[s] ? r[s](d, function(s){return f[s] && f[s]();}) : f[s] ? f[s]() : "%" + (s && s + "%");
    });
}

JavaScript 等于v1.0

/**************************************
* Jonas Raoni Soares Silva
* http://www.joninhas.ath.cx
**************************************/

equals = function(a, b){
    for(var j, o = arguments, i = o.length, c = a instanceof Object; --i;)
        if(a === (b = o[i]))
            continue;
        else if(!c || !(b instanceof Object))
            return false;
        else for(j in b)
            if(!equals(a[j], b[j]))
                return false;
    return true;
};

JavaScript Argumentos opcionales enunafunción

var funcEjemplo = function(nombre){
    //Si el segundo argumento de la función contiene algo lo tenemos.
    //De lo contrario opciones es un objeto vacío.
    var opciones = arguments[1] || {};

    //Asignamos las opciones a variables normales o ponemos valores por defecto
    var saludo = opciones.saludo || "Hola";
    var mensaje = opciones.mensaje || "¿Qué tal?";

    //Hacemos algo supuestamente útil ;D
    alert(saludo + " " + nombre + ". " + mensaje);
}

funcEjemplo("Sendoa", { saludo: "Agur", mensaje: "Ondo pasa!" } );

JavaScript JavaScript重定向

<script type="text/javascript"> 
     // taken from http://evolt.org/article/list/20/416/ 
         // <![CDATA[ 
     var Splash = GetCookie('SplashSkip'); 
     var ReDirected = GetCookie('SplashReDirected'); 
  
     ReDirect('/welcome'); 
  
     function ReDirect (URL) { 
  
         SetCookie('SplashSkip','TRUE',1); 
  
         if (Splash == 'TRUE' && ReDirected != 'TRUE' ) { 
             SetCookie('SplashReDirected','TRUE'); 
             window.location=(URL); 
         } 
     } 
  
     function getCookieVal (offset) { 
       var endstr = document.cookie.indexOf (";", offset); 
       if (endstr == -1) 
         endstr = document.cookie.length; 
       return unescape(document.cookie.substring(offset, endstr)); 
     } 
  
     function GetCookie (name) { 
       var arg = name + "="; 
       var alen = arg.length; 
       var clen = document.cookie.length; 
       var i = 0; 
       while (i < clen) { 
       var j = i + alen; 
       if (document.cookie.substring(i, j) == arg) 
         return getCookieVal (j); 
       i = document.cookie.indexOf(" ", i) + 1; 
       if (i == 0) break; 
       } 
       return null; 
     } 
  
     function SetCookie(name, value, expDays, path, domain, secure) { 
         // Set cookie with name, value etc provided 
         // in function call and date from above 
         // Number of days the cookie should persist NB expDays='' or undef. => non-persistent 
         if (expDays != null ) { 
             var expires = new Date(); 
             expires.setTime(expires.getTime() + (expDays*24*60*60*1000)); 
         }    
         var curCookie = name + "=" + escape(value) + 
             ((expires) ? "; expires=" + expires.toGMTString() : "") + 
             ((path) ? "; path=" + path : "") + 
             ((domain) ? "; domain=" + domain : "") + 
             ((secure) ? "; secure" : ""); 
         document.cookie = curCookie; 
     } 
         // ]]> 
     </script>

JavaScript 重定向cookie

<script type="text/javascript">
	// adapted from http://evolt.org/article/list/20/416/
		// <![CDATA[
	var Splash = GetCookie('SplashSkip');


	ReDirect('/welcome');

	function ReDirect (URL) {

		SetCookie('SplashSkip','TRUE',1);

		if (Splash == 'TRUE') {

			window.location=(URL);
		}
	}

	function getCookieVal (offset) {
	  var endstr = document.cookie.indexOf (";", offset);
	  if (endstr == -1)
	    endstr = document.cookie.length;
	  return unescape(document.cookie.substring(offset, endstr));
	}

	function GetCookie (name) {
	  var arg = name + "=";
	  var alen = arg.length;
	  var clen = document.cookie.length;
	  var i = 0;
	  while (i < clen) {
	  var j = i + alen;
	  if (document.cookie.substring(i, j) == arg)
	    return getCookieVal (j);
	  i = document.cookie.indexOf(" ", i) + 1;
	  if (i == 0) break; 
	  }
	  return null;
	}

	function SetCookie(name, value, expDays, path, domain, secure) {
		// Set cookie with name, value etc provided
		// in function call and date from above
		// Number of days the cookie should persist NB expDays='' or undef. => non-persistent
		if (expDays != null ) {
			var expires = new Date(); 
			expires.setTime(expires.getTime() + (expDays*24*60*60*1000));
		}	
		var curCookie = name + "=" + escape(value) +
			((expires) ? "; expires=" + expires.toGMTString() : "") +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			((secure) ? "; secure" : "");
		document.cookie = curCookie;
	}
		// ]]>
	</script>

JavaScript 正则表达式简单字符串搜索/替换转义方法(使用RE速度增强 - 预编译)

RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\\\' + specials.join('|\\\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\\\$1');
}

JavaScript array_insert

Array.prototype.insert = function( index, item ) {
	this.splice( index, 0, item );
}

var arr = [ 1, 2, 3, 4, 5 ];
alert( arr.insert( 3, 6 ) ); // 1,2,3,6,4,5

JavaScript string_camelize

String.prototype.camelize = function( ) {
	return this.replace( /-([a-z])/g,
		function( $0, $1 ) { return $1.toUpperCase( ) } );
}

alert( "get-element-by-id".camelize( ) ); 
//getElementById

JavaScript string_center,rjust,ljust

String.prototype.ljust = function( width, padding ) {
	padding = padding || " ";
	padding = padding.substr( 0, 1 );
	if( this.length < width )
		return this + padding.repeat( width - this.length );
	else
		return this;
}
String.prototype.rjust = function( width, padding ) {
	padding = padding || " ";
	padding = padding.substr( 0, 1 );
	if( this.length < width )
		return padding.repeat( width - this.length ) + this;
	else
		return this;
}
String.prototype.center = function( width, padding ) {
	padding = padding || " ";
	padding = padding.substr( 0, 1 );
	if( this.length < width ) {
		var len		= width - this.length;
		var remain	= ( len % 2 == 0 ) ? "" : padding;
		var pads	= padding.repeat( parseInt( len / 2 ) );
		return pads + this + pads + remain;
	}
	else
		return this;
}

alert( "Ruby".center( 10 ) );      // "   Ruby   "
alert( "Ruby".rjust( 10 ) );       // "      Ruby"
alert( "Ruby".ljust( 10 ) );       // "Ruby      "
alert( "Ruby".center( 10, "+" ) ); // "+++Ruby+++"

JavaScript 新对话

If DonorType(0).Checked Then
		If Dialog("donorType") <> "" And Dialog("donorType") <> typeIndividual Then
			ResetDialogInfo		
		End If
		Dialog("donorType") = typeIndividual
		Dialog.GoNext("dialog-new-ind1.htm")
	Else
		If Dialog("donorType") <> "" And Dialog("donorType") <> typeOrganization Then
			ResetDialogInfo		
		End If
		Dialog("donorType") = typeOrganization
		Dialog.GoNext("dialog-new-org1.htm")
	End If