// DOM Elements
const inputText = document.getElementById('inputText');
const wordCount = document.getElementById('wordCount');
const charCount = document.getElementById('charCount');
const charNoSpaceCount = document.getElementById('charNoSpaceCount');
const sentenceCount = document.getElementById('sentenceCount');
const paragraphCount = document.getElementById('paragraphCount');
const readingTime = document.getElementById('readingTime');
const inputCharCount = document.getElementById('inputCharCount');
const avgWordLength = document.getElementById('avgWordLength');
const avgSentenceLength = document.getElementById('avgSentenceLength');
const longestWord = document.getElementById('longestWord');
const frequentWord = document.getElementById('frequentWord');
// Buttons
const clearBtn = document.getElementById('clearBtn');
const pasteBtn = document.getElementById('pasteBtn');
const sampleBtn = document.getElementById('sampleBtn');
const refreshBtn = document.getElementById('refreshBtn');
const copyBtn = document.getElementById('copyBtn');
const downloadBtn = document.getElementById('downloadBtn');
const shareBtn = document.getElementById('shareBtn');
const printBtn = document.getElementById('printBtn');
const speakBtn = document.getElementById('speakBtn');
const uploadBtn = document.getElementById('uploadBtn');
const fileUpload = document.getElementById('fileUpload');
const themeToggle = document.getElementById('themeToggle');
const historySelect = document.getElementById('historySelect');
// Sample Text
const sampleText = `This is a sample text for the Word Counter Tool. You can type or paste your own text in this area to see real-time statistics.
The tool will count:
- Words (total words)
- Characters (with and without spaces)
- Sentences (based on punctuation)
- Paragraphs (based on line breaks)
- Reading time (at 200 words per minute)
Try typing something to see the counts update instantly! This is a free online tool that works 100% in your browser. No data is sent to any server.`;
// Initialize
let textHistory = JSON.parse(localStorage.getItem('wordCounterHistory')) || [];
// Update Statistics
function updateStatistics() {
const text = inputText.value;
// Word Count
const words = text.trim() ? text.trim().split(/\s+/) : [];
const wordCountValue = words.length;
// Character Count
const charCountValue = text.length;
const charNoSpaceValue = text.replace(/\s+/g, '').length;
// Sentence Count
const sentences = text.split(/[.!?]+/).filter(s => s.trim().length > 0);
const sentenceCountValue = sentences.length;
// Paragraph Count
const paragraphs = text.split(/\n+/).filter(p => p.trim().length > 0);
const paragraphCountValue = paragraphs.length;
// Reading Time (200 WPM)
const readingTimeValue = Math.ceil(wordCountValue / 200);
// Update DOM
wordCount.textContent = wordCountValue.toLocaleString();
charCount.textContent = charCountValue.toLocaleString();
charNoSpaceCount.textContent = charNoSpaceValue.toLocaleString();
sentenceCount.textContent = sentenceCountValue.toLocaleString();
paragraphCount.textContent = paragraphCountValue.toLocaleString();
readingTime.textContent = readingTimeValue + ' min';
inputCharCount.textContent = charCountValue + ' characters';
// Advanced Statistics
if (wordCountValue > 0) {
// Average Word Length
const totalWordLength = words.reduce((sum, word) => sum + word.length, 0);
const avgWordLen = (totalWordLength / wordCountValue).toFixed(1);
avgWordLength.textContent = avgWordLen;
// Average Sentence Length
const avgSentLen = sentenceCountValue > 0 ? (wordCountValue / sentenceCountValue).toFixed(1) : '0';
avgSentenceLength.textContent = avgSentLen;
// Longest Word
const longest = words.reduce((longest, word) => word.length > longest.length ? word : longest, '');
longestWord.textContent = longest.replace(/[^\w]/g, '') || '-';
// Most Frequent Word
const wordFreq = {};
words.forEach(word => {
const cleanWord = word.toLowerCase().replace(/[^\w]/g, '');
if (cleanWord) {
wordFreq[cleanWord] = (wordFreq[cleanWord] || 0) + 1;
}
});
const mostFrequent = Object.keys(wordFreq).reduce((a, b) => wordFreq[a] > wordFreq[b] ? a : b, '');
frequentWord.textContent = mostFrequent || '-';
} else {
avgWordLength.textContent = '0';
avgSentenceLength.textContent = '0';
longestWord.textContent = '-';
frequentWord.textContent = '-';
}
// Save to history if text is meaningful
if (wordCountValue > 5 && !textHistory.includes(text)) {
textHistory.unshift(text);
if (textHistory.length > 10) textHistory.pop();
localStorage.setItem('wordCounterHistory', JSON.stringify(textHistory));
updateHistoryDropdown();
}
}
// Update History Dropdown
function updateHistoryDropdown() {
historySelect.innerHTML = '';
textHistory.forEach((text, index) => {
const preview = text.substring(0, 50) + (text.length > 50 ? '...' : '');
const option = document.createElement('option');
option.value = text;
option.textContent = `Text ${index + 1}: ${preview}`;
historySelect.appendChild(option);
});
}
// Event Listeners
inputText.addEventListener('input', updateStatistics);
clearBtn.addEventListener('click', () => {
inputText.value = '';
updateStatistics();
inputText.focus();
});
pasteBtn.addEventListener('click', async () => {
try {
const clipboardText = await navigator.clipboard.readText();
inputText.value = clipboardText;
updateStatistics();
} catch (err) {
alert('Unable to paste. Please paste manually (Ctrl+V).');
}
});
sampleBtn.addEventListener('click', () => {
inputText.value = sampleText;
updateStatistics();
});
refreshBtn.addEventListener('click', updateStatistics);
copyBtn.addEventListener('click', () => {
const results = `
Word Counter Results:
Words: ${wordCount.textContent}
Characters (with spaces): ${charCount.textContent}
Characters (no spaces): ${charNoSpaceCount.textContent}
Sentences: ${sentenceCount.textContent}
Paragraphs: ${paragraphCount.textContent}
Reading Time: ${readingTime.textContent}
`.trim();
navigator.clipboard.writeText(results)
.then(() => {
const originalText = copyBtn.innerHTML;
copyBtn.innerHTML = ' Copied!';
setTimeout(() => {
copyBtn.innerHTML = originalText;
}, 2000);
});
});
downloadBtn.addEventListener('click', () => {
const results = `
Word Counter Report
Generated on: ${new Date().toLocaleString()}
Text Preview: ${inputText.value.substring(0, 200)}...
STATISTICS:
• Words: ${wordCount.textContent}
• Characters (with spaces): ${charCount.textContent}
• Characters (without spaces): ${charNoSpaceCount.textContent}
• Sentences: ${sentenceCount.textContent}
• Paragraphs: ${paragraphCount.textContent}
• Reading Time: ${readingTime.textContent}
• Average Word Length: ${avgWordLength.textContent}
• Average Sentence Length: ${avgSentenceLength.textContent}
• Longest Word: ${longestWord.textContent}
• Most Frequent Word: ${frequentWord.textContent}
---
Generated by AllTools Word Counter
https://alltools.com/word-counter
`.trim();
const blob = new Blob([results], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `word-counter-report-${new Date().getTime()}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
shareBtn.addEventListener('click', () => {
if (navigator.share) {
navigator.share({
title: 'Word Counter Results',
text: `My text has ${wordCount.textContent} words, ${charCount.textContent} characters.`,
url: window.location.href
});
} else {
alert('Share feature is not available in your browser. Copy the URL instead.');
}
});
printBtn.addEventListener('click', () => {
window.print();
});
speakBtn.addEventListener('click', () => {
if ('speechSynthesis' in window) {
const utterance = new SpeechSynthesisUtterance(inputText.value.substring(0, 200));
speechSynthesis.speak(utterance);
} else {
alert('Text-to-speech is not supported in your browser.');
}
});
uploadBtn.addEventListener('click', () => {
fileUpload.click();
});
fileUpload.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (event) => {
inputText.value = event.target.result;
updateStatistics();
};
reader.readAsText(file);
}
});
historySelect.addEventListener('change', (e) => {
if (e.target.value) {
inputText.value = e.target.value;
updateStatistics();
}
});
// Theme Toggle
themeToggle.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
if (document.body.classList.contains('dark-mode')) {
themeToggle.innerHTML = ' Light Mode';
localStorage.setItem('theme', 'dark');
} else {
themeToggle.innerHTML = ' Dark Mode';
localStorage.setItem('theme', 'light');
}
});
// Load saved theme
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
document.body.classList.add('dark-mode');
themeToggle.innerHTML = ' Light Mode';
}
// FAQ Toggle
document.querySelectorAll('.faq-question').forEach(question => {
question.addEventListener('click', () => {
question.parentElement.classList.toggle('active');
});
});
// Initialize
updateStatistics();
updateHistoryDropdown();
// Auto-save text every 10 seconds (optional)
setInterval(() => {
if (inputText.value.trim().length > 0) {
localStorage.setItem('wordCounterLastText', inputText.value);
}
}, 10000);
// Load last text
const lastText = localStorage.getItem('wordCounterLastText');
if (lastText) {
inputText.value = lastText;
updateStatistics();
}