JavaScript
Article
By Sam Deering

jQuery.get() Read Text File Example

By Sam Deering

JQuery code snippet to read a text file via the built in AJAX jQuery.get() call and then process the txt file line by line. The example adds the lines to a html element for display on page.

Important: The jQuery code will only replace the first occurrence of the word (jQuery4u) and not every occurrence like PHP’s str_replace() would. To replace every occurrence of a string in JavaScript, you must provide the replace() method a regular expression with a global modifier as the first parameter as such:

.replace(/jQuery4u/g,'jQuery4u FTW!');
--ADVERTISEMENT--

jQuery Code to read text file line by line

jQuery.get('file.txt', function(data) {
   alert(data);
   //process text file line by line
   $('#div').html(data.replace('n','
')); });

Note: Browsers restrict access to local drives (and to server drives) for security reasons. However, you can use the standard jQuery ajax call $.ajax().

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account