JavaScript代码格式化

2012-03-19  金城  3186

<HTML><HEAD><TITLE>JS Formater</TITLE>
</HEAD>
<BODY>
<SCRIPTlanguage=JavaScript>
<!--


functionCLASS_FORMAT(code){
//哈希表类
functionHashtable(){
this._hash=newObject();
this.add=function(key,value){
if(typeof(key)!="undefined"){
if(this.contains(key)==false){
this._hash[key]=typeof(value)=="undefined"?null:value;
returntrue;
        }else{
returnfalse;
        }
       }else{
returnfalse;
       }
      }
this.remove=function(key){deletethis._hash[key];}
this.count=function(){vari=0;for(varkinthis._hash){i++;}returni;}
this.items=function(key){returnthis._hash[key];}
this.contains=function(key){returntypeof(this._hash[key])!="undefined";}
this.clear=function(){for(varkinthis._hash){deletethis._hash[k];}}

 }

this._caseSensitive=true;

//字符串转换为哈希表
this.str2hashtable=function(key,cs){

var_key=key.split(/,/g);
var_hash=newHashtable();
var_cs=true;


if(typeof(cs)=="undefined"||cs==null){
   _cs=this._caseSensitive;
  }else{
   _cs=cs;
  }

for(variin_key){
if(_cs){
    _hash.add(_key[i]);
   }else{
    _hash.add((_key[i]+"").toLowerCase());
   }

  }
return_hash;
 }

//获得需要转换的代码
this._codetxt=code;

if(typeof(syntax)=="undefined"){
  syntax="";
 }

this._deleteComment=false;
//是否大小写敏感
this._caseSensitive=true;
//可以后面加块语句的关键字
this._blockElement=this.str2hashtable("switch,if,while,try,finally");
//是函数申明
this._function=this.str2hashtable("function");
//本行括号内分号不做换行
this._isFor="for";

this._choiceElement=this.str2hashtable("else,catch");

this._beginBlock="{";
this._endBlock="}";

this._singleEyeElement=this.str2hashtable("var,new,return,else,delete,in,case");
//得到分割字符
this._wordDelimiters=" ,.?!;://<>(){}[]"'=+-|*%@#$^&";
//引用字符
this._quotation=this.str2hashtable("",'");
//行注释字符
this._lineComment="//";
//转义字符
this._escape="/";
//多行引用开始
this._commentOn="";
//行结束词
this._rowEnd=";";

this._in="in";


this.isCompress=false;
this.style=0;

this._tabNum=0;


this.format=function(){
varcodeArr=newArray();
varword_index=0;
varhtmlTxt=newArray();

if(this.isCompress){
this._deleteComment=true;
  }


//得到分割字符数组(分词)
for(vari=0;i <this._codetxt.length;i++){
if(this._wordDelimiters.indexOf(this._codetxt.charAt(i))==-1){  //找不到关键字
if(codeArr[word_index]==null||typeof(codeArr[word_index])=='undefined'){
     codeArr[word_index]="";
    }
    codeArr[word_index] +=this._codetxt.charAt(i);
   }else{
if(typeof(codeArr[word_index]) !='undefined' &&codeArr[word_index].length >0)
     word_index++;
    codeArr[word_index++]=this._codetxt.charAt(i);
   }
  }


varquote_opened=false; //引用标记
varslash_star_comment_opened=false; //多行注释标记
varslash_slash_comment_opened=false; //单行注释标记
varline_num=1;  //行号
varquote_char="";  //引用标记类型

varfunction_opened=false;

varbracket_open=false;
varfor_open=false;

//按分割字,分块显示
for(vari=0;i <=word_index;i++){
//处理空行(由于转义带来)
if(typeof(codeArr[i])=="undefined"||codeArr[i].length==0){
continue;
   }elseif(codeArr[i]==" "||codeArr[i]==" "){
if(slash_slash_comment_opened||slash_star_comment_opened){
if(!this._deleteComment){
      htmlTxt[htmlTxt.length]=codeArr[i];
     }
    }
if(quote_opened){
      htmlTxt[htmlTxt.length]=codeArr[i];
    }
   }elseif(codeArr[i]==" "){
//处理换行
   }elseif(codeArr[i]==" "){
    slash_slash_comment_opened=false;
    quote_opened=false;
    line_num++;
if(!this.isCompress){
     htmlTxt[htmlTxt.length]=" "+this.getIdent();
    }
//处理function里的参数标记
   }elseif(!slash_slash_comment_opened&&!slash_star_comment_opened &&!quote_opened &&this.isFunction(codeArr[i])){
    htmlTxt[htmlTxt.length]=codeArr[i] + " ";
    function_opened=true;
   }elseif(!slash_slash_comment_opened&&!slash_star_comment_opened &&!quote_opened &&codeArr[i]==this._isFor){
    htmlTxt[htmlTxt.length]=codeArr[i];
    for_open=true;
   }elseif(!slash_slash_comment_opened&&!slash_star_comment_opened &&!quote_opened &&codeArr[i]=="("){
    bracket_open=true;
    htmlTxt[htmlTxt.length]=codeArr[i];
   }elseif(!slash_slash_comment_opened&&!slash_star_comment_opened &&!quote_opened &&codeArr[i]==")"){
    bracket_open=false;
    htmlTxt[htmlTxt.length]=codeArr[i];
   }elseif(!slash_slash_comment_opened&&!slash_star_comment_opened &&!quote_opened &&codeArr[i]==this._rowEnd){
if(!this.isCompress){
if(!for_open){
if(i<word_index&&(codeArr[i+1]!=" "&&codeArr[i+1]!=" ")){
       htmlTxt[htmlTxt.length]=codeArr[i] + " " +this.getIdent();
      }else{
       htmlTxt[htmlTxt.length]=codeArr[i] +this.getIdent();
      }
     }else{
      htmlTxt[htmlTxt.length]=codeArr[i];
     }
    }else{
     htmlTxt[htmlTxt.length]=codeArr[i];
    }
   }elseif(!slash_slash_comment_opened&&!slash_star_comment_opened &&!quote_opened &&codeArr[i]==this._beginBlock){
    for_open=false;
if(!this.isCompress){
switch(this.style){
case0:
this._tabNum++;
       htmlTxt[htmlTxt.length]=codeArr[i] + " " +this.getIdent();
break;
case1:
       htmlTxt[htmlTxt.length]=" " +this.getIdent();
this._tabNum++;
       htmlTxt[htmlTxt.length]=codeArr[i] + " "+this.getIdent();
break;
default:
this._tabNum++;
       htmlTxt[htmlTxt.length]=codeArr[i];
break;

     }
    }else{
     htmlTxt[htmlTxt.length]=codeArr[i];
    }

   }elseif(!slash_slash_comment_opened&&!slash_star_comment_opened &&!quote_opened &&codeArr[i]==this._endBlock){
if(!this.isCompress){
this._tabNum--;
if(i<word_index&&codeArr[i+1]!=this._rowEnd){
      htmlTxt[htmlTxt.length]=" " +this.getIdent() + codeArr[i];
     }else{
      htmlTxt[htmlTxt.length]=" " +this.getIdent() + codeArr[i];
     }
    }else{
if(i<word_index&&codeArr[i+1]!=this._rowEnd){
      htmlTxt[htmlTxt.length]=codeArr[i] +this._rowEnd;
     }else{
      htmlTxt[htmlTxt.length]=codeArr[i];
     }
    }
//处理关键字
   }elseif(!slash_slash_comment_opened&&!slash_star_comment_opened &&!quote_opened &&this.isBlockElement(codeArr[i])){
    htmlTxt[htmlTxt.length]=codeArr[i];
//处理内置对象(后面加一个空格)
   }elseif(!slash_slash_comment_opened&&!slash_star_comment_opened &&!quote_opened &&this.isSingleEyeElement(codeArr[i])){
if(codeArr[i]==this._in){
     htmlTxt[htmlTxt.length]=" ";
    }
    htmlTxt[htmlTxt.length]=codeArr[i] + " ";
//处理双引号(引号前不能为转义字符) 
   }elseif(!slash_star_comment_opened&&!slash_slash_comment_opened&&this._quotation.contains(codeArr[i])){
if(quote_opened){
//是相应的引号
if(quote_char==codeArr[i]){
      htmlTxt[htmlTxt.length]=codeArr[i];
      quote_opened=false;
      quote_char="";
     }else{
      htmlTxt[htmlTxt.length]=codeArr[i];
     }
    }else{
     htmlTxt[htmlTxt.length]= codeArr[i];
     quote_opened=true;
     quote_char=codeArr[i];
    }
//处理转义字符
   }elseif(codeArr[i]==this._escape){
    htmlTxt[htmlTxt.length]=codeArr[i];
if(i<word_index-1){
if(codeArr[i+1].charCodeAt(0)>=32&&codeArr[i+1].charCodeAt(0)<=127){
      htmlTxt[htmlTxt.length]=codeArr[i+1].substr(0,1);
      htmlTxt[htmlTxt.length]=codeArr[i+1].substr(1);
      i=i+1;
     }
    }
//处理多行注释的开始
   }elseif(!slash_slash_comment_opened &&!slash_star_comment_opened&&!quote_opened&&this.isStartWith(this._commentOn,codeArr,i)){
    slash_star_comment_opened=true;
if(!this._deleteComment){
     htmlTxt[htmlTxt.length]=this._commentOn;
    }
    i=i +this.getSkipLength(this._commentOn);
//处理单行注释
   }elseif(!slash_slash_comment_opened &&!slash_star_comment_opened&&!quote_opened&&this.isStartWith(this._lineComment,codeArr,i)){
    slash_slash_comment_opened=true;
if(!this._deleteComment){
     htmlTxt[htmlTxt.length]=this._lineComment;
    }
    i=i +this.getSkipLength(this._lineComment);
//处理忽略词
   }elseif(!slash_slash_comment_opened &&!slash_star_comment_opened&&!quote_opened&&this.isStartWith(this._ignore,codeArr,i)){
    slash_slash_comment_opened=true;
    htmlTxt[htmlTxt.length]=this._ignore;
    i=i +this.getSkipLength(this._ignore);
//处理多行注释结束 
   }elseif(!quote_opened&&!slash_slash_comment_opened&&this.isStartWith(this._commentOff,codeArr,i)){
if(slash_star_comment_opened){
     slash_star_comment_opened=false;
if(!this._deleteComment){
      htmlTxt[htmlTxt.length]=this._commentOff;
     }
     i=i +this.getSkipLength(this._commentOff);
    }
   }else{
//不是在字符串中
if(!quote_opened){
//如果不是在注释重
if(!slash_slash_comment_opened &&!slash_star_comment_opened){
       htmlTxt[htmlTxt.length]=codeArr[i];
//注释中       
     }else{
if(!this._deleteComment){
       htmlTxt[htmlTxt.length]=codeArr[i];
      }
     }
    }else{
       htmlTxt[htmlTxt.length]=codeArr[i];
    }
   }

  }

returnhtmlTxt.join("");
 }

this.isStartWith=function(str,code,index){

if(typeof(str)!="undefined"&&str.length>0){
varcc=newArray();
for(vari=index;i<index+str.length;i++){
    cc[cc.length]=code[i];
   }
varc=cc.join("");
if(this._caseSensitive){
if(str.length>=code[index].length&&c.indexOf(str)==0){
returntrue;
    }
   }else{
if(str.length>=code[index].length&&c.toLowerCase().indexOf(str.toLowerCase())==0){
returntrue;
    }
   }
returnfalse;

  }else{
returnfalse;
  }
 }

this.isFunction=function(val){
re turnthis._function.contains(this._caseSensitive?val:val.toLowerCase());
 }

this.isBlockElement=function(val){
returnthis._blockElement.contains(this._caseSensitive?val:val.toLowerCase());
 }

this.isChoiceElement=function(val){
returnthis._choiceElement.contains(this._caseSensitive?val:val.toLowerCase());
 }

this.isSingleEyeElement=function(val){
returnthis._singleEyeElement.contains(this._caseSensitive?val:val.toLowerCase());
 }

this.isNextElement=function(from,word){
for(vari=from;i<word.length;i++){
if(word[i]!=" "&&word[i]!=" "&&word[i]!=" "&&word[i]!=" "){
returnthis.isChoiceElement(word[i]);
   }
  }
returnfalse;
 }

this.getSkipLength=function(val){
varcount=0;
for(vari=0;i<val.length;i++){
if(this._wordDelimiters.indexOf(val.charAt(i))>=0){
    count++;
   }
  }
if(count>0){
   count=count-1;
  }
returncount;
 }

this.getIdent=function(){
varn=[];
for(vari=0;i<this._tabNum;i++){
   n[n.length]=" ";
  }
returnn.join("");
 }
}

functiondoformat(o){
varhtmltxt="";

if(o==null){
  alert("domNode is null!");
return;
 }

var_codetxt="";

if(typeof(o)=="object"){
switch(o.tagName){
case"TEXTAREA":
case"INPUT":
    _codetxt=o.value;
break;
case"DIV":
case"SPAN":
    _codetxt=o.innerText;
break;
default:
    _codetxt=o.innerHTML;
break;
  }
 }else{
  _codetxt=o;
 }

var_syn=newCLASS_FORMAT(_codetxt);
 htmltxt=_syn.format();
return htmltxt;
}


functiongo()
{
varcode=document.getElementById("code").value;
varxx=newCLASS_FORMAT(code);
vara=newDate();

if(document.getElementById('cboOperate').selectedIndex==1){
  xx.isCompress=true;
 }else{
  xx.style=parseInt(document.getElementById('cboStyle').value);
 }
 document.getElementById("display").value=xx.format();
 alert("共花:" + (newDate().getTime()-a.getTime()) + "ms");
}
//-->
</SCRIPT>
<TEXTAREAid=coderows=12cols=100>



function xx  (num,str){//说明
var a=num;this.aa=a;
this.bb=function(){alert(str);}
this.cc=function(){for(var i=0;i<10;i++){document.title=i;}}};

xx.prototype.dd=function(){alert("d d  kd");}

var a
=newxx(100,"hello"),b=newxx(0,"ttyp");
if(1
>2){  alert();
}
else{
alert(" hell ");
}

a.bb();
b.dd();
alert(a.aa);

</TEXTAREA><BR>
<selectid="cboOperate"onchange="if(this.selectedIndex==1)document.getElementById('cboStyle').disabled=true;else document.getElementById('cboStyle').disabled=false;">
<optionvalue="0">格式化</option>
<optionvalue="1">压缩</option>
</select>
<selectid="cboStyle">
<optionvalue="0">经典</option>
<optionvalue="1">微软</option>
</select>
<INPUTonclick=go()type=buttonvalue=go><br>
<textareaid=displayrows=12cols=100>
</textarea>
</BODY></HTML>