问题
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