Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript read specific line in txt file and assign an id to it

I have a text file structured like so...

Hello
.
world
.
.
.
.
its me

I using the following code to read the txt file

<head>
<script type="text/javascript">
    function readfileautomatically();
</script>
</head>

<body>
<body onload="readfileautomatically();">

<td id="foo"></td>



<script>
function readfileautomatically () {

var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
alert(client.responseText);
       }
client.send();

}

</script>
</body>

Currently with the above I'm able to read the text file and alert the contents. I want to now expand my code and do this.

read foo.txt when page loads

assign line 3 world from the txt file id=line3

assign line 1 hello from the txt file id=line1

So that I can do this:

<td="line3"> world from txt file will be here  </td>
<td="line1"> hello from txt file will be here  </td>

Any help given would be greatly appreciated.

like image 997
bub ling Avatar asked Mar 16 '23 00:03

bub ling


2 Answers

Let me know if you had any questions :)

<html>
<head>
</head>
<body onload="readfileautomatically();">

<div id="line1"></div>
<div id="line3"></div>

<script>
    function readfileautomatically () {
        var client = new XMLHttpRequest();
        client.open('GET', '/foo.txt');
        client.onreadystatechange = function()
        {
            if( client.responseText != '' )
            {
                var txt = client.responseText.split("\n");
                document.getElementById("line1").innerHTML = txt[0];
                document.getElementById("line3").innerHTML = txt[2];
            }
        }
        client.send();
    }
</script>
</body>
</html>
like image 168
Maziyar Mk Avatar answered Mar 17 '23 20:03

Maziyar Mk


To split the file into lines, you can try the String#split method, splitting by \n characters (newlines). This would give you an array of lines.

For instance:

var text = client.responseText;
var lines = text.split("\n"); // create array of lines
document.getelementById("line3").innerHTML = lines[2]; // Arrays start at zero
document.getelementById("line1").innerHTML = lines[0];
like image 29
PitaJ Avatar answered Mar 17 '23 21:03

PitaJ