如何用jQuery/JS从动态数组中匹配指定数组内的单词?
Hey there! I know you've spent nearly 8 hours grinding on this—let's get this sorted out for you quickly. Here's a straightforward, efficient way to tackle this problem with vanilla JS (no jQuery required, though it works just as well if you prefer using it):
Step 1: Generate the Dynamic Message Array
First, we’ll take your chat string, split it into individual words, convert everything to lowercase (to match your example’s case insensitivity), and clean up any empty entries (in case of accidental multiple spaces).
// Example chat string loaded from your script const chatInput = "Hello my name is Peter"; // Convert to dynamic array: split, lowercase, filter out empty strings const messageArray = chatInput.split(' ') .map(word => word.toLowerCase()) .filter(word => word.length > 0);
Step 2: Set Up Your Target Match Array
This is your fixed array—we’ll keep it as is, but if you want to enforce full case insensitivity (in case your target array ever has mixed casing), you could convert these entries to lowercase too (though your example already aligns with the lowercased dynamic array).
// Your fixed target array (max 20 elements) const findArray = ['hello', 'peter'];
Step 3: Find Matching Words
We’ll use the filter() method to check each word in the dynamic array against the target array. For better performance (especially if your target array hits the 20-element limit), converting the target array to a Set will make lookups faster (O(1) instead of O(n)):
Basic Version (Simple, perfect for small arrays)
const matchedWords = messageArray.filter(word => findArray.includes(word));
Optimized Version (Faster for larger target arrays)
// Convert target array to a Set for quicker lookups const targetSet = new Set(findArray); const matchedWords = messageArray.filter(word => targetSet.has(word));
Handling Edge Cases
If your chat strings include punctuation (like Hello, my name is Peter!), you’ll want to strip non-alphanumeric characters first to ensure accurate matches:
const messageArray = chatInput.split(' ') .map(word => word.toLowerCase().replace(/[^a-z0-9]/g, '')) // Remove punctuation .filter(word => word.length > 0);
Example Output
Running the code with your sample input will give you:
console.log(matchedWords); // Output: ['hello', 'peter']
That’s it! This should cover all your requirements. Let me know if you need to adjust anything for your specific chat script setup.
内容的提问来源于stack exchange,提问作者Peter Bennett

