0

I have 3 files the "root" is my github, so they're all online:

  • Root/blah/blah/index.html
  • Root/blah/blah/document.txt
  • Root/blah/blah/script.js

I want the .js to turn the contents of the .txt into a set of strings separated by the word "END" and print all the strings inside their own <p> </p> in the simplest possible javascript.

I feel like this is really basic but I looked forever for the simplest solution and all the answers are way too complicated or rely on a local text file being uploaded by the user.

All my files are in the same directory.

Sorry if my question is bad. It's my first.

The .txt file could be an html file if that's easier.

I would want the .txt file separated once it got to the word "END" example.txt:

The quick

END

Brown Fox

END

And have that turn into

<p>The Quick</p> <p>Brown Fox</p>
  • is this node.js? Or are you wanting the client to fetch the document.txt separately via AJAX? Also, what is the format of the .txt file. If a .txt file becomes "a set of strings", it is separated by new-lines? Commas? What? – Wyck Nov 24 '20 at 17:20
  • @Wyck I would want the .txt file separated once it got to the word "END" example.txt: The quick END Brown Fox END And have that turn into

    The Quick

    Brown Fox

    . I'm not sure what to use, but Ideally once I linked the script.js in my index.html, it would print all the entries from the .txt up to the "END."
    – Joseph Goulette Nov 24 '20 at 18:01
  • This needs more focus. I see three completely separate problems here. **1)** How to read a .txt file in JavaScript (the answer will be dependent on whether you are running your JavaScript in the browser, or in Node.js, as well as where the file is stored - client or server) **2)** How to parse the text to identify regions of text separated by `END`. **3)** How to update your document with `

    ` elements for each region of text that you identified. (This will depend on the framework you are using. e.g.: React or jQuery or plain JS or whatever.)

    – Wyck Nov 24 '20 at 19:46
  • @wyck it's all in the browser. The point is to get the txt file into the html file so when a webpage loads it's populated with the content of the txt file but I can't use an iframe because it needs to be formatted. I know how, in theory, to do each thing. It's getting them together that's hard. I could make a python program to do it but I want to make my browser do it for me using basic html/javascript. I'm sorry if I was unclear. I spent hours googling it and all the answers were how to have a user upload a text file. – Joseph Goulette Nov 26 '20 at 15:08
  • [This answer](https://stackoverflow.com/a/26298948/1563833) shows how to open a local text file without uploading it. It uses [FileReader](https://developer.mozilla.org/en-US/docs/Web/API/FileReader). – Wyck Nov 26 '20 at 18:06

3 Answers3

0

You can use FS for reading the file, and using the split function for getting an array with the text you desire to print

https://stackabuse.com/read-files-with-node-js/(I hope this link helps you)

0

Reading 'text' files with JS is possible if you load the files from a server using AJAX code. If you don't have a server or wish to load the file locally, you can include the 'text' information in a JS file as a template string.

The following has all the information in a single file but you could easily move the 'script' section to an external file (be sure to remove the tags externally) and load with a tag which includes a src="textfilename.js"

<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0, user-scalable=yes"/>
<title> Test Page </title>
<!-- From: https://stackoverflow.com/questions/64991486/javascript-to-turn-txt-file-into-set-split-by-the-word-end -->
</head><body>
<div id="display"></div>

<script>
// TEXT information included in a JS file as a template string
const textLines = `TEXT lines
Using lines that end with normal CR/LF sequence
Contained in a .JS file
and read as a 'template string'`
</script>

<script>
const textArr = textLines.split('\n');
textArr.forEach( x => document.getElementById('display').innerHTML +=  '<p>'+x+'<br>END</p>');
</script>

</body></html>

BTW, welcome to the discussions

jmrker
  • 472
  • 4
  • 11
0

for answering your question I used "XMLHttpRequest" method of javascript. for running the code that I would post, you need a "localhost" in your PC. in the below at first I refer the links for more information about "localhost" , "XMLHttpRequest", and "split" method of javascript:

https://make.wordpress.org/core/handbook/tutorials/installing-a-local-server/

https://www.w3schools.com/js/js_ajax_http.asp

https://www.w3schools.com/jsref/jsref_split.asp

and here is the code. I used a txt file with random text(named mytext.txt) you could replace the text with your text:

let demoDiv = document.getElementById("demo");
function showText() {
var xhttp = new XMLHttpRequest(); // creating http request
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log("successful");
        let respon = this.responseText; // all text in the file
        let splitArr = respon.split("END"); // split text and makes an array of them
        let lengthArr = splitArr.length;
        for (let i = 0; i < lengthArr; i++) {
            let tempoText = splitArr[i].trim(); // triming the text for deleting extra spaces at the begin and end of it.
            let pTag = document.createElement("p");
            pTag.innerHTML = tempoText;
            demoDiv.append(pTag);
        }
    }
  };
  xhttp.open("GET", "mytext.txt", true);
  xhttp.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Html-file</title>
</head>
<body>
   
   <button onclick="showText()">show</button>
    <div id="demo">
        
    </div>
    
    <script src="readTxt.js"></script>
</body>
</html>

to work with this code you need to install a localhost program like "WAMP" and also create text file yourself. this is the text file I used:

start1 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Omnis dicta ratione, suscipit nostrum aspernatur natus consequatur nulla earum mollitia accusantium voluptatum aut rem officiis pariatur animi accusamus ab, cum vitae sed, assumenda? Exercitationem similique aspernatur, repellat itaque quae mollitia laudantium tempore! Possimus ipsa illum, nam ipsam recusandae adipisci culpa dolore quidem dolorem consequuntur iste nihil. text1 END     start2 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Omnis dicta ratione, suscipit nostrum aspernatur natus consequatur nulla earum mollitia accusantium voluptatum aut rem officiis pariatur animi accusamus ab, cum vitae sed, assumenda? Exercitationem similique aspernatur, repellat itaque quae mollitia laudantium tempore! Possimus ipsa illum, nam ipsam recusandae adipisci culpa dolore quidem dolorem consequuntur iste nihil.  text2 END

start3 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Omnis dicta ratione, suscipit nostrum aspernatur natus consequatur nulla earum mollitia accusantium voluptatum aut rem officiis pariatur animi accusamus ab, cum vitae sed, assumenda? E repellat itaque quae mollitia laudantium tempore! Possimus ipsa illum, nam ipsam recusandae adipisci culpa dolore quidem dolorem consequuntur iste nihil. text3                    END

start4      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Omnis dicta ratione, suscipit nostrum aspernatur natus consequatur nulla earum mollitia accusantium voluptatum aut rem officiis pariatur animi accusamus ab, cum vitae sed, assumenda? Exercitationem similique aspernatur, repellat itaque quae mollitia laudantium tempore! Possimus ipsa illum, nam ipsam recusandae adipisci culpa dolore quidem dolorem consequuntur iste nihil.  text4 END
hamid-davodi
  • 1,602
  • 2
  • 12
  • 26