首页 > 解决方案 > 有没有办法将文本文档写入屏幕并在文档中搜索特定单词并打印出这些单词

问题描述

document.getElementById('inputfile').addEventListener('change', function() {
  var fr = new FileReader();
  fr.onload = function() {
    document.getElementById('output').textContent = fr.result;
  }
  fr.readAsText(this.files[0]);
})
<input type="file" name="inputfile" id="inputfile">
<br>

<pre id="output"></pre>

这是我现有的将文档内容显示到屏幕上的代码

标签: javascripthtmljquery

解决方案


fr.result一个字符串。您可以使用 将此字符串拆分为单词数组String.split(' ')。并检查这些单词中的任何一个是否与您的预定义单词匹配,这些单词也应该在数组中使用Array.some(checkingFunction). 这是您的代码的延续

let myWords = ['hello', 'world', 'what', 'is', 'happening'];
function checkIfWordExistInmyWords(word){
   return myWords.includes(word);
 }
let docWords = fr.result.split(' ');
console.log(docWords.some(checkIfWordExistInmyWords))

推荐阅读