You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

特定单词过滤统计功能实现问询:基于现有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 targetWords array 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:18:56