几天前做的MD解释器拿出来和大家交流一下吧。现在已经实现了标题、段落和换行、强调、分隔线
MarkDown的内容请看这里http://www.oschina.net/question/100267_75314
目前还很不完善,不过重要功能都已经实现了,其他功能也就不在话下了。
最近没时间搞这个了,我也是云六的,自荐信只拿了7分,真愁人。
- <!DOCTYPE html>
- <html>
- <head>
- <title>MarkWown</title>
- </head>
- <body>
- <textarea style="width: 400px;height: 300px" id="rawtext"></textarea> <p>
- <input type="button" value="submit" onclick="Compiler=new compiler('rawtext','OutputHTML');
- Compiler.encode()">
- <div id="OutputHTML"></div>
- <script>
- function compiler(mid,pid){
- var rawlist=document.getElementById(mid);
- var raws="";
- var rawi=0;
- var regexlst;
- var mdbox=document.getElementById(pid);
- var passline=[];
- dict=[
- {"match":/^#{1,6}/,"value":"_ishead()"},
- {"match":/^\*{3,}$/,"value":"_outkit('<hr/>')"},
- {"match":/^\-{3,}$/,"value":"_outkit('<hr/>')"},
- {"match":/^[\* ]*$/,"value":"_outkit('<hr/>')"},
- {"match":/((^(\*|\_){1,3})|((\*|\_){1,3}$))/g,"value":"_textstype()"},
- {"match":/^\- \- \-/,"value":"_outkit('<hr/>')"}
- ];
- function getrawstring(){
- if(rawlist.value==""){
- return 0;
- }
- mdbox.innerText="";
- rawlist=rawlist.value.split("\n")
- _encode();
- }
- //处理文字样式
- function _textstype(){
- if(regexlst.length<2||regexlst[0].length==0||regexlst[1].length==0){
- _outkit(raws);
- }else{
- lst=Min(regexlst[0].length,regexlst[1].length);
- raws=raws.substring(lst[0],raws.length-lst[0])
- switch (lst[0]){
- case 1:
- _outkit("<em>"+raws+"</em>");break;
- case 2:
- _outkit("<strong>"+raws+"</strong>");break;
- case 3:
- _outkit("<em><strong>"+raws+"</strong></em>");
- }
- }
- }
- //图片处理
- function _isimage(){
- }
- //处理开头
- function _ishead(){
- mf=regexlst[0].length;
- _outkit("<h"+mf+">"+raws.substr(mf)+"</h"+mf+">");
- }
- function _outkit(html){
- mdbox.innerHTML+=html;
- }
- //处理-和=的情况
- function _ismaintitle(){
- for(raw in rawlist){
- if(rawlist[raw-1]!=undefined){
- if(rawlist[raw].match(/^\-{1,}$/)!=null){
- passline.push(raw-1);
- rawlist[raw-1]="<h2>"+rawlist[raw-1]+"</h2>"
- rawlist.splice(raw,1);
- }else if(rawlist[raw].match(/^\={1,}$/)!=null){
- passline.push(raw-1);
- rawlist[raw-1]="<h1>"+rawlist[raw-1]+"</h1>"
- rawlist.splice(raw,1);
- }
- }
- }
- }
- //最小的数
- function _sort(a, b){
- return a - b
- }
- function Min(){
- var ilist=[]
- for(i in arguments)
- ilist.push(arguments[i])
- return ilist.sort(_sort);
- }
- //判断array是否存在某个item
- function isExist(arr,item){
- var sum=0;
- for(i in arr){
- if(arr[i]===item)
- sum++;
- }
- return sum;
- }
- function _encode(){
- _ismaintitle();
- for(rawi in rawlist){
- raws=rawlist[rawi];
- if(raws==""){
- _outkit("<p>");
- continue;
- }
- if(isExist(passline,rawi)){
- _outkit(raws);
- continue;
- }
- for(j in dict){
- if((regexlst=raws.match(dict[j].match))!=null){
- eval(dict[j].value);
- break;
- }
- if(j==(dict.length-1))
- _outkit(raws);
- }
- }
- }
- this.encode=getrawstring;
- }
- </script>
- </body>
- </html>
复制代码 |