Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a text file using javascript

The code below is to read a text file using javascript. it works. However, I just want to read part of the content. For example, the content of the file is :"Hello world!" I just want to display "Hello". I tried function split(), but it only works on strings. I don't know how to insert it here.

 var urls = ["data.txt"];

function loadUrl() {
    var urlToLoad = urls[0];
    alert("load URL ... " + urlToLoad);
    browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}

thank you!!!

like image 332
qwerty123 Avatar asked Jul 15 '13 07:07

qwerty123


People also ask

How do you parse text in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

Can I read text file using JavaScript?

The FileReader API can be used to read a file asynchronously in collaboration with JavaScript event handling.


1 Answers

I used

jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});

, and got data from my text file.

Or try this

JQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.

Untested, but the general gist of it...

var HTML_FILE_URL = '/whatever/html/file.html';

$(document).ready(function() {
    $.get(HTML_FILE_URL, function(data) {
        var fileDom = $(data);
        fileDom.find('h2').each(function() {
            alert($(this).text());
        });
    });
});
like image 180
Padmanathan J Avatar answered Sep 23 '22 10:09

Padmanathan J