Is there a way to count words inside a Microsoft Word document using JavaScript? I was able to count words in a normal text file, but I'm wondering if it's possible to do the same for a Microsoft Word file using something like the "JavaScript API for Office" or any other method.
Check out this Plunker example: https://plnkr.co/edit/5TJfNiPxv275GuimdIlj?p=preview
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h2>Counting Words in Microsoft Word Documents Using JavaScript</h2>
<input type="file" accept=".doc,.txt,.docx" onchange="calculateWords()" id="textDoc"/>
<div>
<h1 id="fileInformation">File Word Count After Selection</h1>
</div>
</body>
</html>
JavaScript Code
function calculateWords() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
console.log("words");
var doc = document.getElementById("textDoc");
var f = doc.files[0];
if (!f) {
alert("Failed to load file");
//validate file types yet to come
} else if (false) {
alert(f.type + " is not a valid text file.");
} else {
var r = new FileReader();//create file reader object
r.readAsText(f);//read file as text
//attach function to execute when loading file finishes.
r.onload = function (e) {
var contents = e.target.result;
var res = contents.split(" ");
console.log(res.length);
var fileInformation = "Word Count = "+res.length;
var info = document.getElementById("fileInformation");
info.innerHTML = fileInformation;
}
}
} else {
alert('The File APIs are not fully supported by your browser.');
}
}