i have file in local server (this same directory). I will have 1000 numbers in file
data.txt
123
456
677
I'd like to load this data into the table using JS and create a table
let table = [123, 456, 677]
i have file in local server (this same directory). I will have 1000 numbers in file
data.txt
123
456
677
I'd like to load this data into the table using JS and create a table
let table = [123, 456, 677]
I'm going to assume that you want to do this on a browser.
To do it, you'd read the file as text via ajax, then parse it into an array by splitting on line breaks, then parse the lines as numbers via parseInt
or similar.
For example:
fetch("data.txt")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.text();
})
.then(text => {
table = text.split(/[\r\n]+/) // Split into lines
.filter(line => line.trim()) // Remove blank lines
.map(str => parseInt(str)); // Parse lines to numbers
// Use table here...
})
.catch(error => {
// ...handle/report error here
});
parseInt
isn't your only option for parsing the strings, see my answer here for a list of your various options and their pros and cons.
More to explore: