特定单词过滤统计功能实现问询:基于现有JavaScript函数优化
Optimized
countWords() Function for Targeted Word Counting Got it, let's tweak your function to only count the specific words you care about—like and or immigration—while fixing some edge cases like punctuation and case differences. Here's the refined version:
function countWords() { // Define your target words here (easily editable) const targetWords = ['and', 'immigration']; const text = document.querySelector('textarea').value; const outputDiv = document.getElementById('output'); // Handle empty input case if (!text.trim()) { outputDiv.innerHTML = '<p>Please enter some text to analyze!</p>'; return; } outputDiv.innerHTML = ''; const wordCounts = {}; // Initialize counts for all target words to 0 (so even unused words show up) targetWords.forEach(word => { wordCounts[word.toLowerCase()] = 0; }); // Process each word in the input text text.replace(/\S+/g, rawWord => { // Clean the word: strip trailing punctuation and normalize to lowercase const cleanedWord = rawWord.replace(/[.,!?;:"']+$/, '').toLowerCase(); // Only increment count if the word is in our target list if (targetWords.includes(cleanedWord)) { wordCounts[cleanedWord]++; } }); // Render the final counts Object.entries(wordCounts).forEach(([word, count]) => { const resultPara = document.createElement('p'); resultPara.textContent = `${word}: ${count}`; outputDiv.appendChild(resultPara); }); }
Key Improvements Breakdown:
- Target Word Flexibility: The
targetWordsarray lets you easily add/remove words without rewriting core logic. - Case Insensitivity: Converting all words to lowercase ensures matches like "And", "AND", and "and" are counted as the same word.
- Better Punctuation Handling: The regex
/[.,!?;:"']+$/strips all common trailing punctuation in one go (instead of just splitting on dots and commas). - Empty Input Feedback: Shows a clear message if the textarea is empty, instead of leaving the output blank.
- Consistent Output: Initializes all target word counts to 0, so you'll see every target word listed even if it doesn't appear in the text.
内容的提问来源于stack exchange,提问作者Bryan Sanders
相关产品推荐
相关产品推荐

