jQuery.get() Read Text File Example

Sam Deering
Tweet

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().

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • midnight007

    good tip, i have a question
    how i can read each line and stored in a array variable?
    greetings from mexico.

  • http://blogradiovn.com blog radio

    hello.
    i want read file txt using jquery.please help me. i can’t do it.:(
    my code read a line in file txt.i want read more line in file contact.txt

    test

    $(document).ready(function() {
    $(“#driver”).click(function(event){
    $(‘#stage’).load(‘contact.txt’);
    });
    });

    STAGE

    • http://jquery4u.com/ jQuery4u

      Try using the AJAX get code above and change the filename to contact,txt and #div to #stage.
      If you still have any problems let me know.

  • Sudersoh

    very helpful, I have a question, I want to write into a text file of a specific drive and read also from there

  • Robert Fletcher

    What if the file you want to read is on the another domain? How do you handle reading text files using jquery across domains?

    • http://jquery4u.com/ jQuery4u

      Hi Robert, the best way would be to use JSONP which allows cross domain AJAX calls, you would however need to wrap your text in JSON like so

      {
      “text”: text json encoded
      }

  • http://www.facebook.com/vuhuyphong Phong Juskteez

    How can I read each word in a text?
    For example I have a text like “jQuery4u is so awesome!” so how can I export to html like “JQuery4uissoawesome!
    Thanks!

    • Derek Welty

      .replace(‘ ‘,”);

  • tejal

    how to write in file using jquery

  • Ata

    The right syntact at line by line:
    …replace(/n/g, “”)

  • Attila

    hi
    lines = data.split(“n”);