使用ajax从文本文件中读取特定单词

时间:2011-12-20 05:49:29

标签: javascript ajax

我正在尝试使用ajax读取文本文件并且工作正常,但我想知道有没有办法使用ajax从文件中读取特定的单词或句子。

谢谢

1 个答案:

答案 0 :(得分:1)

好的,你想从每一行得到最后一个字。假设您已经通过Ajax检索了文件并将其作为字符串粘贴在变量中:

var fileString = // whatever you did to retrieve it

然后你可以使用正则表达式来匹配每一行的最后一个单词,忽略单词后面的标点符号(但记住单词可能包含撇号)并记住一行可能只有一个单词,可能是这样的:

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

或者您可以将字符串拆分为行并将空格上的每一行拆分以获取最后一个单词,然后删除其他标点符号:

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

两种方法的演示合并为一个jsfiddle:http://jsfiddle.net/4qcpH/

鉴于我基本上已经为你完成了所有工作,我将留给你查询how the regex works,以及.split()如何运作。

使用任何一种解决方案,您可能需要调整它以处理额外的标点符号等等。