格式化并将文本文件附加到contenteditable div中

时间:2013-09-29 10:35:31

标签: javascript html

如何格式化获取的本地文本文件(文本格式的C ++代码)以在我的contenteditable div中正确格式化(就像粘贴事件所做的那样,它带来了所需的格式)。

function readSingleFile(evt) {

    var f = evt.target.files[0];
      console.log(f);
       if (!f) {
        alert("Failed to load file");
           return;
    } 
      if (f.name.indexOf('.txt') == -1) {
            alert(f.name + " is not a valid text file.");
             return;     
                  }    

      var r = new FileReader();
      r.onload = function(e) { 
          var contents = e.target.result.replace("\n","<br/>");
        alert( "Got the file.n" 
              +"name: " + f.name + "n"
              +"type: " + f.type + "n"
              +"size: " + f.size + " bytesn"
              + "contents: " + contents
        );
          document.getElementById('board').innerHTML = contents;
      }
      r.readAsText(f);

  }

  document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
http://jsfiddle.net/vinodlouis/88vtR/3/

https://stackoverflow.com/users/2523444/vinod-louis

尝试将此字符串作为要打开的文本文件。它丢失了一些字符串(由于没有使用html实体?)

#include<iostream.h>
#include<conio.h>

int main(){

int grade, passingMark=75;

cout<<"Hi there, please enter your mark: ";
cin>>grade;

if( ((grade >= passingMark)||(grade==35)) && (grade<101)){
cout<<"\nPass!";
}

else if( (grade==74) ){
    cout<<endl<<"Almost!";
}

else if( (grade>0) && (grade<70)){
cout<<endl<<"Super Failed!";
}

return 0;
}    

1 个答案:

答案 0 :(得分:4)

我建议这样的事情:

http://jsfiddle.net/88vtR/4/

文件显示在<PRE>中且文件内容为“符合html实体”

换句话说

var contents = e.target.result;//.replace("\r\n","<br/>");
contents = contents.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');

<pre id="board" contenteditable = "true">
paste the chosen text file here
</pre>

I dont see any difference between the two files