JavaScript - 打开文件,搜索字符串并打印下一个单词

时间:2018-02-18 20:03:57

标签: javascript html ajax string

所以我正在寻找一些帮助...我想要做的是打开一个本地存储在我的服务器上的文件。在文件中查找特定单词,然后在找到该特定单词时打印下一个单词。

我的代码会打开文件,但会打印该文件中的所有内容。

<td class="hidden-phone">
<div id="test">
</div>
</td>

<script type="text/javascript">
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
function loadFile() {
    reader.open('get', 'http://xxxxxxxxx:xxxxx/log-file.txt', true);
    reader.onreadystatechange = displayContents;
    reader.send(null);
}
function displayContents() {
    if(reader.readyState==4) {
        var el = document.getElementById('test');
        el.innerHTML = reader.responseText;
    }
}
</script>

如果符合以下条件,请在log-file.txt中说:

Hello
Apples
World
foobar

我希望能够打开该文件,搜索苹果这个词,如果找到则打印下一个世界词。

1 个答案:

答案 0 :(得分:0)

您可以通过空格分隔符将内容拆分为字符串数组,大致为“单词”,然后遍历数组,当您要查找的字符串(单词)发生时,存储下一个数组项:

var wanted = 'Apples';
var words = reader.responseText.split(/\s/);
var found = [];
words.forEach(function (word, index) {
    // if we've got the match and the next item exists (we're not at the end of the array)
    if (word === wanted && words[index + 1])
        // push the next item (word) to the "wanted" array
        found.push(words[index + 1]);
});
// join the results with line break elements and stuff them to el
document.getElementById('test').innerHTML = found.join('<br/>');

如果您需要搜索多个wanted字词,请使用array&amp; indexOf

var wanted = ['Apples', 'Onions'];
// ...
    if (wanted.indexOf(word) !== -1 && words[index + 1])

(如果找不到该元素,indexOf将返回-1。)

你的例子有更多的问题,其中最大的问题是reader分散在几个函数中,通常最好将它保存在一个地方并将接收到的内容传递给“业务逻辑”函数(在onreadystatechange回调内),所以更新的例子:

<button onclick="loadFile()">Load file</button>
<div id="test"></div>

<script>
function loadFile() {
    var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
    reader.open('get', '/log-file.txt', true);
    reader.onreadystatechange = function () {
        if (reader.readyState == 4 && reader.status == 200) {
            displayContents(reader.responseText);
        }
    };
    reader.send();
}

function displayContents(content) {
    var wanted = 'Apples';
    var words = content.split(/\s/);
    var found = [];
    words.forEach(function (word, index) {
        // if we've got the match and the next item exists (we're not at the end of the array)
        if (word === wanted && words[index + 1]) {
            // push the next item (word) to the "wanted" array
            found.push(words[index + 1]);
        }
    });
    // join the results with line break elements and stuff them to el
    console.log('found:', found);
    var el = document.getElementById('test');
    el.innerHTML = found.length ? found.join('<br/>') : 'nothing found';
}
</script>