<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>color keywords</title>
<style type="text/css">
* {
font-family: "新宋体";
}#txtCode{
width : 100%;
height: 200px;
resize: vertical;
}.Output{
border : 1px solid #396;
color  : white;
width : 100%;
resize : both;
font-size : 16px;
line-height : 150%;
background-color:#0B161D;
}Span.Comments{
color:#159AE0
}Span.String{
color:#27A735;
}Span.RegExp{
color:#EA842B;
}Span.Keywords{
color:#FFAA00;
}Span.Number{
color:#9C3583;
}Span.Operator{
color:#8CBBAD;
}
</style><script type="text/javascript">
function colorKeywords(){
var keywords = "Array|arguments|alert|window|document|location|Boolean|Date|Enumerator|Error|Function|Global|Math|Number|Object|RegExp|String|break|delete|function|return|typeof|case|do|if|switch|var|catch|else|in|this|void|continue|false|instanceof|throw|while|debugger|finally|new|true|with|default|for|null|try|abstract|double|goto|native|static|boolean|enum|implements|package|super|byte|export|import|private|synchronized|char|extends|int|protected|print|throws|class|final|interface|public|transient|const|float|long|short|volatile";

        //解析优先级: 注释 > 字符串 > 正则 > 关键字 > 数字 > 运算符
        var regStr  = "(/\\*[\\S\\s]*?\\*/|//.*?\\r?\\n)"
 + "|((?:\"(?:[^\"]*?\\\\\")*.*?\")|(?:'(?:[^']*?\\\\')*.*?'))"
 + "|(/(?:[^/]+?\\\\/)*.*?/[a-zA-Z]*)"
 + "|(\\b(?:"+keywords+")\\b)"
 + "|(\\b\\d+\\b)"
 + "|(\\+\\+|--|===|==|\\+=|-=|\\*=|%=|~=|\\^=|\\|=|\\+|\\-|\\*|%|=|\\?|\\:|\\{|\\}|\\(|\\)|\\[|\\]|&&|&|\\|\\||\\|)";

var reg = new RegExp(regStr, "gi");
var source = $("txtCode").value;
if( source == "" ) return;

var ds = new Date();
//着色前对特殊字符:<、>进行处理,否则格式会乱掉。
source = source.replace(/</g, "&lt;")
   .replace(/>/g, "&gt;");

//对关键字进行着色
var output = source.replace(reg, function(){
var args  = [].slice.call(arguments, 0);
var lstIdx = args[args.length - 2];
var match   = args[0];

if( args[1] ) return "<span class='Comments'>" + args[1] + "</span>";
if( args[2] ) return "<span class='String'>" + args[2] + "</span>";
if( args[3] ) return "<span class='RegExp'>" + args[3] + "</span>";

if( args[4] ) return  (source.charAt(lstIdx-1) != "$")
                     ? "<span class='Keywords'>"+ args[4] + "</span>"
 : match;

if( args[5] ) return  (source.charAt(lstIdx-1) != "$")
 ? "<span class='Number'>" + args[5] + "</span>"
 : match;

if( args[6] ) return "<span class='Operator'>" + args[6] + "</span>";

return match;
   });

//替换掉空格和回车使能够正常格式化输出
output = output.replace(/\r?\n/g, "<br/>" )
   .replace(/\t/g , "&nbsp;&nbsp;&nbsp;&nbsp;")
   .replace(/(<\/?\w+.*?>)|(\s)/g, function($0, $1, $2){
if( $1 ) return $1;
if( $2 ) return "&nbsp;";
});

var de = new Date();

alert("耗时:" + (de - ds));

$("output").innerHTML = output;
}
function $(id){
return document.getElementById(id);
}
function clearOutput(){
$("output").innerHTML=""; 
}
</script>
</head>
<body><input type="button" value="代码着色" onClick="colorKeywords()" />
<input type="button" value="情况输出" onClick="clearOutput()" />
<br/>
<br/>请输入要着色的代码:
<textarea id="txtCode">
/**---------------------------
* test multiline comments
* @author jianbo.wang
*/function(){
   //测试单行注释着色
   
   /**--------------------------
   * 测试多行注释着色.
   *--------------------------*/   //测试字符串着色.
   print("\"hello world!\"");
   print('will output:"hello world!"');
   
   //测试正则着色
   var reg = /(<\/?\w+.*?>)|(\s)/g;
   
   //测试关键字着色
   var output, _window, $window, 
   c= window.alert,  d= $window.alert, e= _window.alert, 
   f= window._alert,  g= $window._alert,  h= _widnow._alert
   i= window.$alert,  j= $window.$alert, k= _window.$alert;
   
   for(var i=0; i<100; i++){
   output = "Welcome user" + i;
       alert(output);    
   }
   
   //测试数字着色
   var a = 100, b= "200", $100, _200, c="$200", d="_100";
   
   
   //运算符着色测试
   var index = 0;
   var user = {
   name : "张三",
   age  : 12,
   index: index++
   };
   
   var a = 0;
   a++; a--; a+="hello"; a+=100; a-=1; a*=1; a%=1;
   (a === 1 ) ? true : false; 
   (a ==  1 ) ? true : false;
   (a =   1 ) ? true : false;
   (a >   1 ) ? true : false;
} function colorKeywords(){
//解析优先级: 注释 > 字符串 > 正则 > 关键字 > 数字 > 运算符
var keywords = "Array|arguments|alert|window|document|location|Boolean|Date|Enumerator|Error|Function|Global|Math|Number|Object|RegExp|String|break|delete|function|return|typeof|case|do|if|switch|var|catch|else|in|this|void|continue|false|instanceof|throw|while|debugger|finally|new|true|with|default|for|null|try|abstract|double|goto|native|static|boolean|enum|implements|package|super|byte|export|import|private|synchronized|char|extends|int|protected|print|throws|class|final|interface|public|transient|const|float|long|short|volatile";
var regStr  = "(/\\*\\*[\\S\\s]*?\\*/|//.*?\\r?\\n)"
 + "|((?:\"(?:[^\"]+?\\\\\")*.*?\")|(?:'(?:[^']+?\\\\')*.*?'))"
 + "|(/(?:[^/]+?\\\\/)*.*?/[a-zA-Z]*)"
 + "|(\\b(?:"+keywords+")\\b)"
 + "|(\\b\\d+\\b)"
 + "|(\\+\\+|--|===|==|\\+=|-=|\\*=|%=|~=|\\^=|\\|=|\\+|\\-|\\*|%|=|\\?|\\:|\\{|\\}|\\(|\\)|\\[|\\])";

var reg = new RegExp(regStr, "gi");
var source = $("txtCode").value;
if( source == "" ) return;

//着色前对特殊字符:<、>进行处理,否则格式会乱掉。
source = source.replace(/</g, "&lt;")
   .replace(/>/g, "&gt;");

//对关键字进行着色
var output = source.replace(reg, function(){
var args = [].slice.call(arguments, 0);
if( args[1] ) return "<span class='Comments'>" + args[1] + "</span>";
if( args[2] ) return "<span class='String'>" + args[2] + "</span>";
if( args[3] ) return "<span class='RegExp'>" + args[3] + "</span>";
if( args[4] ) return "<span class='Keywords'>" + args[4] + "</span>";
if( args[5] ) return "<span class='Number'>" + args[5] + "</span>";
if( args[6] ) return "<span class='Operator'>" + args[6] + "</span>";
return args[0];
   });

//替换掉空格和回车使能够正常格式化输出
output = output.replace(/\r?\n/g, "<br/>" )
   .replace(/\t/g , "&nbsp;&nbsp;&nbsp;&nbsp;")
   .replace(/(<\/?\w+.*?>)|(\s)/g, function($0, $1, $2){
if( $1 ) return $1;
if( $2 ) return "&nbsp;";
});

$("output").innerHTML = output;
}
function $(id){
return document.getElementById(id);
}
function clearOutput(){
$("output").innerHTML=""; 
}
</textarea>
<br/>
<br/>
代码着色结果:
<div id="output" class="Output">
codes output here!
</div></body>
</html>

解决方案 »

  1.   

    还不错,ff速度很快,不过有点bug   for(var i=0; i&lt;100; i++){//这里的"< "要处理吧,变成html代码了
           output = "Welcome user" + i;
           alert(output);       
       }
      

  2.   

    确实有不少成熟的库来做这些事情了,工作中我也不会用成熟的库不用自己这个。
    但用别人的并不等于自己就不应该去如何实现它,过一阵闲了想写一个能够格式化
    和着色html的函数,自己练练手
      

  3.   

    <>总是转换错啊
    放在//后就没问题
      

  4.   

    周末在家无事对代码做了些调整,添加了行号,并修了特殊字符:&lt;, &gt; &不能正常显示的Bug。
    去掉了对原字符串进行replace的次数,减少到只需要一次,理路上来说应该性能会有一些提高。
    <!doctype html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>color keywords</title>
    <style type="text/css">
    * {
        font-family: "新宋体";
    }#txtCode{
        width : 100%;
        height: 200px;
        resize: vertical;
    }.Output :firstword{
    }Span.Comments{
        color:#159AE0
    }Span.String{
        color:#27A735;
    }Span.RegExp{
        color:#EA842B;    
    }Span.Keywords{
        color:#FFAA00;
    }Span.Number{
        color:#9C3583;
    }Span.Operator{
        color:#8CBBAD;
    }Span.LineNo{
    background-color: #2e3436;
    margin-right : 5px;
    color : #8CBBAD;
    }.Output{
        border         : 1px solid #396;
        color          : white;
        resize         : both;
        font-size     : 16px;
        background-color: #0B161D;
    width : 100%;
    overflow : auto;
    word-wrap : no-wrap; /*使不自动换行, 调试中*/
    }
    </style><script type="text/javascript">
    function colorKeywords(){
        var source  = $("txtCode").value;
    if( source == "" ) return;     
    var ds = new Date();

    var keywords  = "Array|arguments|alert|window|document|location|Boolean|Date|Enumerator|Error|Function|Global|Math|Number|Object|RegExp|String|break|delete|function|return|typeof|case|do|if|switch|var|catch|else|in|this|void|continue|false|instanceof|throw|while|debugger|finally|new|true|with|default|for|null|try|abstract|double|goto|native|static|boolean|enum|implements|package|super|byte|export|import|private|synchronized|char|extends|int|protected|print|throws|class|final|interface|public|transient|const|float|long|short|volatile";
    var operators = "\\+\\+|--|===|==|\\+=|-=|\\*=|%=|~=|\\^=|&=|>=|<=|>|<|!=|!|\\|=|\\+|-|\\*|%|=|\\?|\\:|\\{|\\}|\\(|\\)|\\[|\\]|&&|&|\\|\\||\\|";
      
    //解析优先级: 注释 > 字符串 > 正则 > 关键字 > 数字 > 运算符  > \s\n\t等占位符
    var regStr  = "(/\\*[\\S\\s]*?\\*/|//.*?\\r?\\n)"
    + "|((?:\"(?:[^\"]*?\\\\\")*.*?\")|(?:'(?:[^']*?\\\\')*.*?'))"
    + "|(/(?:[^/]+?\\\\/)*.*?/[a-zA-Z]*)"
    + "|(\\b(?:"+keywords+")\\b)"
    + "|(\\b\\d+\\b)"
    + "|("+ operators +")"
    + "|(\\s|\\t|\\r?\\n)";    
        var parseReg= new RegExp(regStr, "g");

    //格式化数字函数
    var formatNo = function(n){
    if( n < 10 ){
    return "&nbsp;&nbsp;&nbsp;&nbsp;" + n;
    }else if( n < 100 ){
    return "&nbsp;&nbsp;&nbsp;" + n;
    }else if( n < 1000){
    return "&nbsp;&nbsp;" + n;
    }else if( n < 10000){
    return "&nbsp;" + n;
    }else{
    return n;
    }
    };

    //处理字符串中的特殊字符,并在需要换行的时候添加行号
    var lineNo = 1;
    var handleStr  = function(source){
    return source.replace(/<|>|&|\s|\t|\r?\n/g, function(match){
    switch( match ){
    case "<"  : return "&lt;" ;
    case ">"  : return "&gt;" ;
    case "&"  : return "&amp;" ;
    case " "  : return "&nbsp;" ;
    case "\t" : return "&nbsp;&nbsp;&nbsp;&nbsp;";
    case "\n" :
    case "\r\n" :
    return "<br/><span class='LineNo'>" + formatNo(++lineNo) + ".</span>";
    }
    });
    }
        
        //对关键字进行着色
        var output = source.replace(parseReg, function(){
    var args    = [].slice.call(arguments, 0);
    var lstIdx  = args[args.length - 2];
    var match   = args[0];
    var preChar = lstIdx > 0 
    ? source.charAt(lstIdx-1)
    : "";

    if( args[1] ) return "<span class='Comments'>"  + handleStr(match) + "</span>";               
    if( args[2] ) return "<span class='String'>"    + handleStr(match) + "</span>";                    
    if( args[3] ) return "<span class='RegExp'>"    + handleStr(match) + "</span>";                    
    if( args[4] ) return  (preChar != "$")
     ? "<span class='Keywords'>"+ match + "</span>"
     : match;                    
    if( args[5] ) return  (preChar != "$")
     ? "<span class='Number'>" + match + "</span>"
     : match;                    
    if( args[6] ) return "<span class='Operator'>" + handleStr(match) + "</span>";
    if( args[7] ) return handleStr(match);                    
    return match;
       });
    output = "<span class='LineNo'>" + formatNo(1) + ".</span>" + output;    

    //计算耗时
    var de = new Date();
    alert("处理字符串耗时:" + (de - ds));

    //输出格式化后的内容
        $("output").innerHTML = output;    
    }function $(id){
        return document.getElementById(id);
    }function clearOutput(){
        $("output").innerHTML=""; 
    }
    </script>
    </head>
    <body><input type="button" value="代码着色" onClick="colorKeywords()"    />
    <input type="button" value="情况输出" onClick="clearOutput()"    />
    <br/>
    <br/>请输入要着色的代码:
    <textarea id="txtCode">
    /**---------------------------
    * test multiline comments
    * @author jianbo.wang
    */function(){
       //测试单行注释着色
       
       /**--------------------------
       * 测试多行注释着色.
       *--------------------------*/   //测试字符串着色.
       print("\"hello world!\"");
       print('will output:"hello world!"');
       
       //测试正则着色
       var reg = /(<\/?\w+.*?>)|(\s)/g;
       
       //测试关键字着色
       var output, _window, $window, 
           c= window.alert,     d= $window.alert,    e= _window.alert, 
           f= window._alert,     g= $window._alert,     h= _widnow._alert
           i= window.$alert,     j= $window.$alert,    k= _window.$alert;
       
       for(var i=0; i<100; i++){
           output = "Welcome user" + i;
           alert(output);       
       }
       
       //测试数字着色
       var $1, $2, _1, _2, a = 100, b= "200", $100, _200, c="$200", d="_100";
       
       
       //运算符着色测试
       var index = 0;
       var user = {
           name : "张三",
           age  : 12,
           index: index++
       };
       
       var a = 0;
       a++; a--; a+="hello"; a+=100; a-=1; a*=1; a%=1; a>=1; a<=1; a > b; a != 2;
       (a === 1    ) ? true : false; 
       (a ==  1    ) ? true : false;
       (a =   1    ) ? true : false;
       (a >   1 ) ? true : false;
       if( a > 1 || a < 0 || (a == "string" && b == "number" ) return false;
    } function colorKeywords(){
        var source  = $("txtCode").value;
    if( source == "" ) return;     
    var ds = new Date();

    var keywords  = "Array|arguments|alert|window|document|location|Boolean|Date|Enumerator|Error|Function|Global|Math|Number|Object|RegExp|String|break|delete|function|return|typeof|case|do|if|switch|var|catch|else|in|this|void|continue|false|instanceof|throw|while|debugger|finally|new|true|with|default|for|null|try|abstract|double|goto|native|static|boolean|enum|implements|package|super|byte|export|import|private|synchronized|char|extends|int|protected|print|throws|class|final|interface|public|transient|const|float|long|short|volatile";
    var operators = "\\+\\+|--|===|==|\\+=|-=|\\*=|%=|~=|\\^=|&=|>=|<=|>|<|!=|!|\\|=|\\+|-|\\*|%|=|\\?|\\:|\\{|\\}|\\(|\\)|\\[|\\]|&&|&|\\|\\||\\|";
      
    //解析优先级: 注释 > 字符串 > 正则 > 关键字 > 数字 > 运算符  > \s\n\t等占位符
    var regStr  = "(/\\*[\\S\\s]*?\\*/|//.*?\\r?\\n)"
    + "|((?:\"(?:[^\"]*?\\\\\")*.*?\")|(?:'(?:[^']*?\\\\')*.*?'))"
    + "|(/(?:[^/]+?\\\\/)*.*?/[a-zA-Z]*)"
    + "|(\\b(?:"+keywords+")\\b)"
    + "|(\\b\\d+\\b)"
    + "|("+ operators +")"
    + "|(\\s|\\t|\\r?\\n)";    
        var parseReg= new RegExp(regStr, "g");

    //格式化数字函数
    var formatNo = function(n){
    if( n < 10 ){
    return "&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;" + n;
    }else if( n < 100 ){
    return "&amp;nbsp;&amp;nbsp;&amp;nbsp;" + n;
    }else if( n < 1000){
    return "&amp;nbsp;&amp;nbsp;" + n;
    }else if( n < 10000){
    return "&amp;nbsp;" + n;
    }else{
    return n;
    }
    };

    //处理字符串中的特殊字符,并在需要换行的时候添加行号
    var lineNo = 1;
    var handleStr  = function(source){
    return source.replace(/<|>|&|\s|\t|\r?\n/g, function(match){
    switch( match ){
    case "<"  : return "&amp;lt;" ;
    case ">"  : return "&amp;gt;" ;
    case "&"  : return "&amp;amp;" ;
    case " "  : return "&amp;nbsp;" ;
    case "\t" : return "&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;";
    case "\n" :
    case "\r\n" :
    return "<br/><span class='LineNo'>" + formatNo(++lineNo) + ".</span>";
    }
    });
    }
        
        //对关键字进行着色
        var output  = source.replace(parseReg, function(){
    var args    = [].slice.call(arguments, 0);
    var lstIdx  = args[args.length - 2];
    var match   = args[0];
    var preChar = lstIdx > 0 
    ? source.charAt(lstIdx-1)
    : "";

    if( args[1] ) return "<span class='Comments'>"  + handleStr(match) + "</span>";               
    if( args[2] ) return "<span class='String'>"    + handleStr(match) + "</span>";                    
    if( args[3] ) return "<span class='RegExp'>"    + handleStr(match) + "</span>";                    
    if( args[4] ) return  (preChar != "$")
     ? "<span class='Keywords'>"+ match + "</span>"
     : match;                    
    if( args[5] ) return  (preChar != "$")
     ? "<span class='Number'>" + match + "</span>"
     : match;                    
    if( args[6] ) return "<span class='Operator'>" + handleStr(match) + "</span>";
    if( args[7] ) return handleStr(match);                    
    return match;
       });
    output = "<span class='LineNo'>" + formatNo(1) + ".</span>" + output;    

    //计算耗时
    var de = new Date();
    alert("处理字符串耗时:" + (de - ds));

    //输出格式化后的内容
        $("output").innerHTML = output;    
    }function $(id){
        return document.getElementById(id);
    }function clearOutput(){
        $("output").innerHTML=""; 
    }
    </textarea>
    <br/>
    <br/>代码着色结果:
    <ol  id="lstNum" class="ListNum"></ol>
    <div id="output" class="Output" >
    codes output here!
    </div></body>
    </html>
      

  5.   

    just  up  it 
      

  6.   

    这个版本对数字的判断还是游戏问题,没有考虑16进制和浮点数,有空的时候会修改这部分的bug.
    当比较稳定之后会再写一个对代码进行格式化代码的函数,这样应用起来会方便一些。代码的格式
    化,要比这个复杂一些,更有挑战性,也是我比较喜欢的。因为格式化代码要复杂些,花的时间也
    要长一些,等写完之后照旧会发一个新帖贴出来,希望大家届时光顾。
      

  7.   

    这两天忙着产品上线,没时间打理帖子,没想到还有关注。谢谢大家的支持,这两天正在看Douglas Crockford
    的一些代码为格式化脚本做一些技术准备。
      

  8.   

    chrom 效率很高啊。待会分析代码学习学习。支持lz
      

  9.   

    抽空做了写小改动,优化了下数字和字符串的处理,使其更精确, 正则部分还有些问题,有空再改吧<!doctype html> 
    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>color keywords </title> 
    <style type="text/css"> 
    * { 
      font-family: "新宋体";

      
    #txtCode{ 
      width : 100%; 
      height: 200px; 
      resize: vertical; 

      
    b.Comments{ 
      color:#159AE0;
      font-weight:500;

      
    b.String{ 
      color:#27A735; 
      font-weight:500;

      
    b.RegExp{ 
      color:#EA842B;
      font-weight:500;  

      
    b.Keywords{ 
      color:#FFAA00;
      font-weight:500;  

      
    b.Number{ 
      color:#9C3583;
      font-weight:500;  

      
    b.Operator{ 
      color:#FFAA00;
      font-weight:500;  

      
    b.LineNo{ 
      background-color : #2e3436; 
      margin-right : 5px; 
      color : #8CBBAD;
      font-weight : 500;  

      
    .Output{ 
      border        : 1px solid #396; 
      color         : white; 
      resize        : both; 
      font-size     : 16px; 
      width : 100%;  
      word-wrap : no-wrap; /*使不自动换行, 调试中*/
      word-break : keep-all;  
      background-color: #0B161D; 

    </style> 
      
    <script type="text/javascript"> 
    function sytaxHightlight(source, outEl, keywords, optrs, cfg){ 
      if((!source || !outEl)
         || !(keywords instanceof Array)
         || !(optrs instanceof Array)
         || keywords.length ===0
         || optrs.length === 0){
        return;
      }
       
      var ds = new Date();
      
      //对关键字和运算符进行排序
      var sortFn = function(i1, i2){return i1 < i2  ? 1 : -1;};   
      keywords = keywords.concat().sort(sortFn);
      optrs    = optrs.concat().sort(sortFn);    //生成解析表达式
      var comntsPattn = '/\\*[\\S\\s]*?\\*/|//.*?\\r?\\n',      
          strPattn    = '\'(?:[^\\\\\'\\n]|\\\\.)*\'|"(?:[^\\\\"\\n]|\\\\.)*"',  
          regPattn    = '/(?:[^/]+?\\\\/)*.*?/[a-zA-Z]*',
          namePattn   = '[_\\$a-zA-Z][_\\$\\w]*',
          
          numberPattn = (function(){
            var haxPart = "0x[0-9a-fA-F]+",
                numPart = "(?:(?:0?\\.\\d+)|(?:[1-9]\\d*(?:\\.\\d+)?))",
                expPart = "(?:(?:e|E)(?:(?:\\+|-)?(?:0|[1-9]\\d*)))?";
                
            return '(?:' + haxPart + ')|(?:' + numPart + expPart + ')';  
          })(),
          
          optrPattn = (function(){
            var i, optr, ret = [], 
                len = optrs.length,
                reg = /(\+|\*|\?|\!|\:|\^|\$|\||\{|\}|\(|\)|\[|\])/g;
            
            for(i = 0; i < len; i++){
              optr = optrs[i];
              if(optr){
                ret.push(optr.replace(reg, "\\$1"));
              }  
            }
            
            return ret.join('|');        
          })(),      
          
          //解析优先级: 注释 > 字符串 > 正则 > 标示符(变量) > 数字 > 运算符  > \s\n\t等占位符
          parseReg   = new RegExp((
              '(' + comntsPattn   + ')' 
      + '|(' + strPattn     + ')' 
      + '|(' + regPattn     + ')' 
      + '|(' + namePattn    + ')' 
      + '|(' + numberPattn  + ')' 
      + '|(' + optrPattn    + ')'  //不需要的话可以去掉此行并相应调整source.replace
      + '|(\\r?\\n|\\s|\\t)'       //注意\s会匹配换行符\n, 因此换行符的匹配需要提前        
          ), 'g'),
          
          //检验标示符是否为关键字
          isKeyWord = (function(){
            var i, len = keywords.length; kwMap = {};
            for(i = 0; i < len; i++){
              kwMap[keywords[i]] = null;
            }
            
            return function(name){
              return kwMap.hasOwnProperty(name);
            };        
          })();  
       
      //格式化数字函数 
      var formatNo = function(n){ 
    if( n < 10 ){ 
    return "&nbsp;&nbsp;&nbsp;&nbsp;" + n; 
    }else if(n  < 100 ){ 
    return "&nbsp;&nbsp;&nbsp;" + n; 
    }else if(n  < 1000){ 
    return "&nbsp;&nbsp;" + n; 
    }else if(n  < 10000){ 
    return "&nbsp;" + n; 
    }else{ 
    return n; 

    }; 
       
      //处理字符串中的特殊字符,并在需要换行的时候添加行号 
      var lineNo   = 1; 
      var handleStr = function(str){
        return str.replace(/<|>|&|\r?\n|\s|\t/g, function(match){ 
          switch( match ){ 
            case "<"  : return "&lt;" ; 
            case ">"  : return "&gt;" ; 
            case "&"  : return "&amp;" ; 
            case " "  : return "&nbsp;" ; 
            case "\t" : return "&nbsp;&nbsp;&nbsp;&nbsp;";
            
            case "\n"   : 
            case "\r\n" : 
              return "<br/><b class='LineNo'>" + formatNo(++lineNo) + ".</b>";  
          } 
        }); 
      };  
        
      //对关键字进行着色 
      var output = source.replace(parseReg, function(){
        var args = arguments, match = args[0];
                
        if (args[1])  return "<b class='Comments'>"  + handleStr(match) + "</b>";
        if (args[2])  return "<b class='String'  >"  + handleStr(match) + "</b>";  
        if (args[3])  return "<b class='RegExp'  >"  + handleStr(match) + "</b>"; 
        if (args[4])  return   isKeyWord(match)
                             ? "<b class='Keywords'>"+ match + "</b>" 
                             : match;       
        if (args[5])  return "<b class='Number'>"   + match  + "</b>";
        if (args[6])  return "<b class='Operator'>" + handleStr(match) + "</b>";
        if (args[7])  return handleStr(match);         return match; 
      }); 
      output = "<b class='LineNo'>" + formatNo(1) + ".</b>" + output;     
       
      //计算耗时 
      var de = new Date();  
      alert("处理字符串耗时:" + (de - ds)); 
       
      //输出格式化后的内容 
      outEl.innerHTML = output;     

      
    //辅助代码---------------------------------------  
    function $(id){ 
        return document.getElementById(id); 

      
    function clearOutput(){ 
        $("output").innerHTML="";  
    }function getStyle(lang){
      var map = {};
      
      map['js'] = map['javascript'] = {
        keywords : (
          "Array|arguments|alert|window|document|location|Boolean|Date|Enumerator|Error|Function|Global|Math|Number|Object|RegExp|String|break|delete|function|return|typeof|case|do|if|switch|var|catch|else|in|this|void|continue|false|instanceof|throw|while|debugger|finally|new|true|with|default|for|null|try|abstract|double|goto|native|static|boolean|enum|implements|package|super|byte|export|import|private|synchronized|char|extends|int|protected|print|throws|class|final|interface|public|transient|const|float|long|short|volatile"
        ).split(/\|/),
        
        optrs : (   
            "+ ++ - -- * / % "
          + "+= -= *= /= %= ^= &= "
          + "^ ! ~ >>> <<< "
          + "> >= < <= != !== === == = "
          + "& && | || "
          + ", ? : ; "
          + "{ } [ ] ( )"
        ).split(/\s+/) 
      };
      
      return map[lang.toLowerCase()];
    }function doHightlight(){
      var source  = $("txtCode").value,
          outEl   = $('output' ),
          style   = getStyle('js'),
          keywords= style.keywords,
          optrs   = style.optrs;
          
      sytaxHightlight(source, outEl, keywords, optrs);  
    }
    </script> 
    </head> 
    <body> 
      
    <input type="button" value="代码着色" onClick="doHightlight()" /> 
    <input type="button" value="清空输出" onClick="clearOutput()"  /> 
    <br/> 
    <br/> 
      
    请输入要着色的代码: 
    <textarea id="txtCode"> 
    /**--------------------------- 
    * test multiline comments 
    * @author jianbo.wang 
    */
      
    function(){ 
       //测试单行注释着色 
        
       /**-------------------------- 
       * 测试多行注释着色. 
       *--------------------------*/ 
      
       //测试字符串着色. 
       print("\"hello world!\""); 
       print('will output:"hello world!"');
       print('hello \\\'world!\\\"')   
       
       //一些错误的字符串
       print('hello \\'world!\\\"')
       print("hello \\"world!\\\"")    
       print('hello world!")
       print("hello world!')  
       print("hello world!)
       print('hello world!)
       print(\'hello world!)   
       print(\"hello world!)
       
       //测试正则着色 
       var reg = /(<\/?\w+.*?>)|(\s)/g; 
         
       //测试关键字着色 
       var output, _window, $window,  
           c= window.alert,     d= $window.alert,    e= _window.alert,  
           f= window._alert,     g= $window._alert,     h= _widnow._alert 
           i= window.$alert,     j= $window.$alert,    k= _window.$alert; 
         
       for(var i=0; i <100; i++){ 
           output = "Welcome user" + i; 
           alert(output);        
       } 
       
       if (a instanceof Array) return true;
       alert(typeof a);
       var a = new String('abc');
         
       //测试数字着色 
       var $1, $2, _1, _2, a100 = 100, b12= "200", $100, _200, c="$200", d="_100"; 
       var nums = [
          0x123, 0xfff, 0x0, 0x12F,   
          .123, 0.56, 100, -11.2, +12.3,
          0.5e16, 0.5E-3, .6E12, .6E-2
       ];
          
         
         
       //运算符着色测试 
       var index = 0; 
       var user = { 
           name : "张三", 
           age  : 12, 
           index: index++ 
       }; 
         
       var a = 0; 
       a++; a--; a+="hello"; a+=100; a-=1; a*=1; a%=1; a>=1; a <=1; a > b; a != 2; 
       (a === 1    ) ? true : false;  
       (a ==  1    ) ? true : false; 
       (a =   1    ) ? true : false; 
       (a >   1 ) ? true : false; 
       if( a > 1 || a  < 0 || (a == "string" && b == "number" ) return false; 
    }  </textarea> 
    <br/> 
    <br/> 
      
    代码着色结果:
    <div id="output" class="Output" > 
      codes output here! 
    </div> 
      
    </body> 
    </html>