87,910
社区成员
发帖
与我相关
我的任务
分享
<!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, "<")
.replace(/>/g, ">");
//对关键字进行着色
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 , " ")
.replace(/(<\/?\w+.*?>)|(\s)/g, function($0, $1, $2){
if( $1 ) return $1;
if( $2 ) return " ";
});
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, "<")
.replace(/>/g, ">");
//对关键字进行着色
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 , " ")
.replace(/(<\/?\w+.*?>)|(\s)/g, function($0, $1, $2){
if( $1 ) return $1;
if( $2 ) return " ";
});
$("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>
<!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 " " + n;
}else if(n < 100 ){
return " " + n;
}else if(n < 1000){
return " " + n;
}else if(n < 10000){
return " " + 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 "<" ;
case ">" : return ">" ;
case "&" : return "&" ;
case " " : return " " ;
case "\t" : return " ";
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>