2025-01-27 20:32:34 +01:00
|
|
|
// Function to count the occurrences of each word in the given text
|
2025-01-27 20:29:15 +01:00
|
|
|
function countWordOccurrences(text) {
|
2025-01-27 20:32:34 +01:00
|
|
|
// Convert text to lowercase and match words using regex
|
2025-01-27 20:29:15 +01:00
|
|
|
const words = text.toLowerCase().match(/\b\w+\b/g);
|
|
|
|
|
const wordCount = {};
|
|
|
|
|
|
2025-01-27 20:32:34 +01:00
|
|
|
// Count each word's occurrences
|
2025-01-27 20:29:15 +01:00
|
|
|
words.forEach(word => {
|
|
|
|
|
wordCount[word] = (wordCount[word] || 0) + 1;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return wordCount;
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-27 20:32:34 +01:00
|
|
|
// Function to display the word count results
|
2025-01-27 20:29:15 +01:00
|
|
|
function displayWordCount(wordCount) {
|
|
|
|
|
const resultDiv = document.getElementById('result');
|
|
|
|
|
resultDiv.innerHTML = ''; // Clear previous results
|
|
|
|
|
|
|
|
|
|
let totalWords = 0;
|
2025-01-27 20:32:34 +01:00
|
|
|
// Iterate through the word count object and display each word and its count
|
2025-01-27 20:29:15 +01:00
|
|
|
for (const [word, count] of Object.entries(wordCount)) {
|
|
|
|
|
totalWords += count;
|
|
|
|
|
const p = document.createElement('p');
|
|
|
|
|
p.textContent = `${word}: ${count}`;
|
|
|
|
|
resultDiv.appendChild(p);
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-27 20:32:34 +01:00
|
|
|
// Display the total number of words
|
2025-01-27 20:29:15 +01:00
|
|
|
const totalP = document.createElement('p');
|
|
|
|
|
totalP.textContent = `Totaal aantal woorden: ${totalWords}`;
|
|
|
|
|
resultDiv.appendChild(totalP);
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-27 20:32:34 +01:00
|
|
|
// Example usage: Add event listener to the button to count words when clicked
|
2025-01-27 20:29:15 +01:00
|
|
|
document.getElementById('countButton').addEventListener('click', () => {
|
|
|
|
|
const text = document.getElementById('textInput').value;
|
|
|
|
|
const wordCount = countWordOccurrences(text);
|
|
|
|
|
displayWordCount(wordCount);
|
|
|
|
|
});
|