[英]How to Count the Number of Words in a Text File using Javascript
I am stock at something here.我在这里有货。
I am trying to integrate a feature on my web application (HTML5) that will enable users choose a text file using normal HTML file input box, and have have the total number of words in the selected text file displayed to them in real-time.我正在尝试在我的 Web 应用程序 (HTML5) 上集成一项功能,该功能将使用户能够使用普通的 HTML 文件输入框选择文本文件,并实时显示所选文本文件中的总字数。
Here is what i have so far on the Javascript part:这是我到目前为止在 Javascript 部分的内容:
<script>
//function to count words in selected text file
$(function() {
$('#upload').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]); //get temp path of selected file
//some codes here to read the file selected by the user and store the number of words in a string called total_word
$("#display_File_count").text(total_word); //display the number of words in the appropriate span
});
});
</script>
here is the HTML part;这是 HTML 部分;
<input name="upload" type="file" id="upload" accept="text/plain" accesskey="u">
<div><span id="display_File_count">0</span> <span> words</span></div>
When the user clicks on the file selector and choose a text file, the script should read the text file's contents count number of words contained in it (all done on client's side).当用户点击文件选择器并选择一个文本文件时,脚本应该读取文本文件的内容,计算其中包含的字数(全部在客户端完成)。
The number of words is then displayed within the span with id "display_file_count".然后在 id 为“display_file_count”的范围内显示单词数。
Please guys I need a way out.请伙计们,我需要一条出路。
Thanks in advance.提前致谢。
I would use the FileReader (remember to check browser compatibility - becuase it is not supported by all browsers)我会使用 FileReader(记得检查浏览器兼容性 - 因为不是所有浏览器都支持它)
$('#upload').change( function(event) {
var f = event.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var res = contents.split(" ");
$("#display_File_count").text(res.length);
}
r.readAsText(f);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.