简体   繁体   中英

To display text from a txt file using javascript

How to read text from a txt file with one button to browse the file and other button to display text. Pls help me in getting the code. i have tried many codes but othing worked. some code was like this. Thanks in advance

<!DOCTYPE html>
<html>
  <head>
    <title>reading file</title>
    <script type="text/javascript">

        var reader = new FileReader();

        function readText(that){

            if(that.files && that.files[0]){
                var reader = new FileReader();
                reader.onload = function (e) {  
                    var output=e.target.result;
                    //process text to show only lines with "@":             
            output=output.split("\n").filter(/./.test, /\@/).join("\n");

                document.getElementById('main').innerHTML= output;
                };//end onload()
                reader.readAsText(that.files[0]);
            }//end if html5 filelist support
        } 
</script>
</head>
<body>
    <input type="file" onchange='readText(this)' />
    <div id="main"></div>
  </body>
</html>

You should properly read an article like this: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Dont think this line is working properly:

output=output.split("\n").filter(/./.test, /\@/).join("\n");

Try changing it to:

output=output.split("\n").filter(function(l) {
    //return /^\@/.test(l); // Starting with @
    return l.indexOf('@') > -1; // Containing @
}).join("\n");

It would be interesting to see if this would work as well:

output=output.split("\n").filter(/\@/.test.bind(/\@/)).join("\n");

The second arguments passed to the .filter method is the context:

array.filter(callback[, thisObject])

Get the input file, use FileReader() to read it,on file load get text that matches the pattern. Finally display it through "main" div. Should work..

HTML :

<input id="fileInput" type="file"/>
<div id="main"></div>

jQuery :

$(function(){
        $("#fileInput").change(function(e){
            var myFile = e.target.files[0];
            var reader = new FileReader();
            reader.onload = function(e){
                var output = e.target.result;
                output=output.split("\n").filter(/./.test, /\@/).join("\n");
                $("#main").text(output);
            };
            reader.readAsText(myFile)
        });
    }
)

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM