Skip to main content

jQuery.get() Read Text File Example

By Sam Deering

JavaScript

Share:

😳 Ever felt a little embarassed sharing your JavaScript? Let's fix it.

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

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

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

💁‍♀️ Fun Fact: Python was ranked #2 on a recent highest paid coders list. *


🤓 Ok. When did a code editor from Microsoft become kinda cool!?