read a local file in javascript and output certain lines from it

孤人 提交于 2021-01-27 18:49:57

问题


I am tasked with a little coding challenge that I can't seem to work out. Its meant to be done in javascript, a language I have touched in years... Basically the task is to read a local file , which has sentences on each line. Some of the sentences are palindromes- and the goal is to output only the sentences that are palindromes. I have tried playing around in JSFiddle with the following code. But, my functionality isn't working.

HTML:

<input type="file" name="file" id="file">

Javascript:

window.addEventListener('load', function() {
    document.getElementById("myBtn").addEventListener("click", function() {

      var reader = new FileReader();
      reader.addEventListener('load', function() {
        document.getElementById('file').innerText = this.result;
      });
      reader.readAsText(document.querySelector('input').files[0]);
    });
}, true);
console.log(reader);

I found some code online for checking palindromes, but its for a user inputted sentence. I'm struggling to comprehend how to utilize this logic to apply to the lines from my inputted file.

function palindrome(str) {
var re = /[\W_]/g;
var lowRegStr = str.toLowerCase().replace(re, '');
var reverseStr = lowRegStr.split('').reverse().join(''); 
return reverseStr === lowRegStr;
}
palindrome("A man, a plan, a canal. Panama");

Any ideas or advice? Thanks!


回答1:


This is a quick solution for the boilerplate code that you got: Sample file contents:

A man, a plan, a canal. Panama
something else
another line

window.addEventListener('load', function() {
    document.getElementById("myBtn").addEventListener("click", function() {

      var reader = new FileReader();
      reader.addEventListener('load', function() {
        //document.getElementById('file').innerText = this.result;
        const strings = this.result.split(/\r?\n/);
        const palindromes = strings.filter((line) => {
          return palindrome(line);
        });
        console.log('initial lines:', strings);
        console.log('palindromes only:', palindromes);
      });
      reader.readAsText(document.querySelector('input').files[0]);
    });
}, true);
//console.log(reader);

function palindrome(str) {
  if (str === '') return false;
  var re = /[\W_]/g;
  var lowRegStr = str.toLowerCase().replace(re, '');
  var reverseStr = lowRegStr.split('').reverse().join(''); 
  return reverseStr === lowRegStr;
}
<input type="file" name="file" id="file">
<button id="myBtn">Start</button>


来源:https://stackoverflow.com/questions/65803506/read-a-local-file-in-javascript-and-output-certain-lines-from-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!