jQuery.get() Read Text File Example

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!');

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','<br>'));
});

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