Reputation: 63
How would I go about adding each individual word from a text file into an array using javascript?
The file is not a csv and contains about 5 lines each with around 5 words. I know that I'll have to use .split(" ")
however because there are multiple lines I'm not sure about the loop.
Thanks in advance
Upvotes: 0
Views: 83
Reputation: 18923
You can simply read the text in a file and then use the following split:
split(/\s+/);
\s
matches both spaces and newlines.
Upvotes: 1
Reputation: 6914
First: define a function to handle the content of the file
function parseTheFileContent(fileData)
{
var lines = fileData.split('\n');
// do something with the lines array
}
Second: make an ajax call to fetch the file content
httpRequest = new XMLHttpRequest();
if (!httpRequest) return;
httpRequest.onreadystatechange = function()
{
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) parseTheFileContent(httpRequest.responseText);
}
}
Upvotes: 0