如何用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
Resultsarray 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
varfor loop variables can lead to unexpected scoping issues (though not breaking here, switching tolet/constis 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
- Input validation: Checks if the input is empty and clears the result list instead of running unnecessary logic.
- Smarter sentence splitting: Uses a regular expression
/[.!?]\s+/to split sentences at proper ending punctuation, not just dots. - No duplicate results: The
filter+somecombo checks each sentence once, so even if it has multiple keywords, it only gets added once. - Cleaner variable declarations: Uses
constfor fixed values andlet(where needed) instead ofvarto avoid scoping bugs. - Safer DOM manipulation: Uses
createElementandtextContentinstead of raw HTML string concatenation—this avoids potential XSS risks and is more maintainable.
内容的提问来源于stack exchange,提问作者Rémi DELCAILLAU
相关产品推荐
相关产品推荐

