Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  12] [ 1]  / answers: 1 / hits: 17349  / 13 Years ago, tue, september 13, 2011, 12:00:00

I have an external textfile of variable length named profiles.txt with information in the following format:



 Jason/Red/Tyrannosaurus
Zack/Black/Mastodon
Billy/Blue/Triceratops
Trini/Yellow/Griffin
(etc)


How can I read through the file using JavaScript to output the following HTML:



 Name: Jason<br>
Color: Red<br>
Avatar: Tyrannosaurus<br>
<br>
Name: Zack<br>
Color: Black<br>
Avatar: Mastodon<br>
<br>
(etc)

More From » html

 Answers
180

Here's an example using XMLHttpRequest:



var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open('GET', test.txt, false);
xmlhttp.send();
document.write(xmlhttp.responseText.split('rn').map(function (i) {return i.replace(/(.+),(.+),(.+)/g, 'Name: $1<br>Color: $2<br>Avatar: $3<br>')} ).join('<br/>'));


Array.map needs to be shim in IE8 and below. Also, IE uses new ActiveXObject(Msxml2.XMLHTTP)
This is a very slimmed down example. I'm using asyc false which is bad and document.write which is bad. But I just wanted to demonstrate getting the file and parsing the input.


[#90117] Monday, September 12, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylanalis

Total Points: 438
Total Questions: 85
Total Answers: 102

Location: Barbados
Member since Sun, Nov 27, 2022
1 Year ago
kylanalis questions
Sat, Oct 2, 21, 00:00, 3 Years ago
Tue, Oct 13, 20, 00:00, 4 Years ago
Thu, Feb 13, 20, 00:00, 4 Years ago
Tue, Jan 7, 20, 00:00, 4 Years ago
;