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

如何用JavaScript提取含特定词汇的句子?求代码修正建议

Hey there! Let's work through your JavaScript code to get it working properly and make it a bit more robust. Here are the key issues with your current code, plus a fixed version with explanations:

What was going wrong in your original code?

  • Duplicate sentences in results: If a single sentence contained multiple keywords (like both "so" and "hence"), it would get added to the Results array multiple times, leading to duplicate list items.
  • Old results don't clear: Every time you clicked the button, new results would append to the old ones instead of replacing them.
  • Rigid sentence splitting: Splitting only on . doesn't account for sentences ending with ! or ?, or abbreviations like "Mr." that use dots but aren't sentence endings.
  • Var scope quirks: Using var for loop variables can lead to unexpected scoping issues (though not breaking here, switching to let/const is better practice).

Fixed Code

HTML (minor tweak for usability)

<input id="enter" type="text" placeholder="Paste your text here...">
<input type="button" value="Extract Conclusion Sentences" onclick="DetectConcl()">
<div id="conclusion">
  <ul></ul>
</div>

JavaScript

function DetectConcl() {
  // Fixed keywords array (const since it won't change)
  const conclusions = ["so", "hence", "as a consequence"];
  const inputText = document.getElementById("enter").value.trim();
  
  // Handle empty input by clearing results and exiting early
  if (!inputText) {
    document.getElementById("conclusion").querySelector("ul").innerHTML = "";
    return;
  }

  // Better sentence splitting: matches .!? followed by whitespace
  const sentences = inputText.toLowerCase().split(/[.!?]\s+/).map(sentence => sentence.trim());

  // Filter sentences that contain ANY of the keywords (no duplicates)
  const matchingSentences = sentences.filter(sentence => {
    return conclusions.some(keyword => sentence.includes(keyword));
  });

  // Clear existing results first
  const resultList = document.getElementById("conclusion").querySelector("ul");
  resultList.innerHTML = "";

  // Add each matching sentence to the list safely
  matchingSentences.forEach(sentence => {
    const listItem = document.createElement("li");
    listItem.textContent = sentence;
    resultList.appendChild(listItem);
  });
}

Key Improvements Explained

  1. Input validation: Checks if the input is empty and clears the result list instead of running unnecessary logic.
  2. Smarter sentence splitting: Uses a regular expression /[.!?]\s+/ to split sentences at proper ending punctuation, not just dots.
  3. No duplicate results: The filter + some combo checks each sentence once, so even if it has multiple keywords, it only gets added once.
  4. Cleaner variable declarations: Uses const for fixed values and let (where needed) instead of var to avoid scoping bugs.
  5. Safer DOM manipulation: Uses createElement and textContent instead of raw HTML string concatenation—this avoids potential XSS risks and is more maintainable.

内容的提问来源于stack exchange,提问作者Rémi DELCAILLAU

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:06:56