me_digvijay
me_digvijay

Reputation: 5492

Read a particular word from a text file using ajax

I am trying to read a text file using ajax and that is working fine, but I want to know that is there any way to read a particular word or sentence from a file using ajax.

Thank You

Upvotes: 0

Views: 1099

Answers (1)

nnnnnn
nnnnnn

Reputation: 150030

OK, you want to get the last word from each line. Assuming you have retrieved the file via Ajax and have stuck it in a variable as a string:

var fileString = // whatever you did to retrieve it

Then you can use a regex to match the last word of each line, ignoring punctuation after the word (but remembering that words may contain apostrophes) and remembering that a line may have just one word in it, perhaps something like this:

var re = /(?:^| )([A-Za-z']+)(?:\W*)$/gm,
    matches = [],
    current;

while ((current = re.exec(fileString)) != null)
    matches.push(current[1]);

// matches array contains the last word of each line

Or you can split the string into lines and split each line on spaces to get the last word, then remove miscellaneous punctuation:

var lines = fileString.split("\n"),
    matches = [];

for (var i = 0; i < lines.length; i++)
    matches.push(lines[i].split(" ").pop().replace(/[^A-Za-z']/g,""));

// matches array contains the last word of each line

Demo of both methods combined into a single jsfiddle: http://jsfiddle.net/4qcpH/

Given that I've basically done all the work for you here I shall leave it to you to look up how the regex works, and how .split() works.

With either solution you'll probably need to tweak it to handle extra punctuation and so forth exactly the way you want to.

Upvotes: 1

Related Questions