简体   繁体   English

如何使用JavaScript打开本地磁盘文件并检查其是否包含我们需要的单词?

[英]How to open a local disk file with JavaScript and check whether it has the word which we needed?

I want to open text or word file in JavaScript. 我想用JavaScript打开文本或Word文件。 After that I want my program to scan that whether it has the word which i needed. 之后,我希望程序扫描它是否包含我需要的单词。 If it has the world then it should produce an alert as word is found,else alert as word is not found. 如果它有世界,那么它应该在找到单词时发出警报,而在没有单词时发出警报。 Please help me in this. 请帮助我。 I wrote an code to read from file.But I'm not sure where the content of file is stored and where to use search function. 我写了一个从文件读取的代码,但是我不确定文件的内容存储在哪里以及在哪里使用搜索功能。

My current code is 我当前的代码是

<h1>File reader</h1>
<div>
    Select a text file: 
    <input type="file" id="fileInput">
    <pre id="displayArea"><pre>
</div>

window.onload = function() {
    var fileInput = document.getElementById('fileInput');
    var displayArea= document.getElementById('fileDisplayArea');

    fileInput.addEventListener('change', function(e) {
        var file = fileInput.files[0];
        var textType = /text.*/;

        if (file.type.match(textType)) {
            var reader = new FileReader();

            reader.onload = function(e) {
                displayArea.innerText = reader.result;
            }
    reader.readAsText(file);                

        } else {
            displayArea.innerText = "File not supported!"
        }
  });
}

by using this I can get my file content in output,But I need output as an alert whether file has the needed word. 通过使用此选项,我可以在输出中获取文件内容,但是我需要输出作为文件是否包含所需单词的警报。

You are doing nothing with your result, thats why you have to store the reader.result output in a variable, then look if the word you are looking for is inside of that output and show the alert. 您对结果不采取任何措施,这就是为什么必须将reader.result输出存储在变量中,然后查看您要查找的单词是否在该输出中并显示警报。

Something like this... 像这样

var readResult = reader.result;

if (/Hello/.test(readResult)) {
  alert("The word exist");
} else {
  alert("The word does not exist");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM