Node.js+Jade应用:匹配词汇后展示后续3个词的实现疑问
Hey there! Let's work through this problem together. I’ll start by assuming you’ve got a basic setup where you’re passing a project array to your Jade template, and you were previously using an if check to match your target word. Here’s how to adjust that logic to show the next 3 words after a match:
First, let’s recap your likely existing code
I bet your template looks something like this, where you’re checking for the target word and displaying the matching item:
// Your original Jade code snippet each item in projects if item.includes('目标词汇') p= item
Solution 1: Handle logic in Node.js backend (recommended)
It’s best practice to keep template logic minimal, so let’s process the array in your Node.js route first:
// Example Node.js route code const projects = ['词汇A', '目标词汇', '后续词1', '后续词2', '后续词3', '词汇B']; const targetWord = '目标词汇'; // Find the index of your target word const targetIndex = projects.indexOf(targetWord); let nextThreeWords = []; // Only grab the next 3 words if the target exists and isn't the last item if (targetIndex !== -1 && targetIndex < projects.length - 1) { // slice(startIndex, endIndex) - endIndex is exclusive, so +4 gives us up to 3 items nextThreeWords = projects.slice(targetIndex + 1, targetIndex + 4); } // Pass the filtered words to your Jade template res.render('your-template-file', { projects, nextThreeWords });
Then in your Jade template, you can directly render the results:
if nextThreeWords.length > 0 h3 匹配到的后续词汇: each word in nextThreeWords p= word else p 未找到目标词汇,或后续词汇不足3个
Solution 2: Handle logic directly in Jade
If you prefer to keep everything in the template, you can do this (though it’s less clean for complex logic):
- const targetWord = '目标词汇'; - const targetIndex = projects.indexOf(targetWord); - let nextThree = []; - // Calculate the next 3 words if target exists - if (targetIndex !== -1) { - nextThree = projects.slice(targetIndex + 1, targetIndex + 4); - } // Render the results if nextThree.length > 0 h3 后续3个词汇: each word in nextThree p= word else p 没有符合条件的内容
Edge case to consider
If your "project array" has items that are full sentences (not single words), you’ll need to split the sentence into words first. For example:
// If each project is a sentence string const projects = ['这是一段包含 目标词汇 的句子 后续词1 后续词2 后续词3', '另一段句子']; const targetWord = '目标词汇'; let nextThreeWords = []; projects.forEach(sentence => { const wordArray = sentence.split(' '); // Split by space - adjust delimiter if needed const targetPos = wordArray.indexOf(targetWord); if (targetPos !== -1) { nextThreeWords = wordArray.slice(targetPos + 1, targetPos + 4); } });
If your project items are objects instead of strings, just adjust the code to check the relevant property (e.g., item.name.includes(targetWord) instead of item.includes(...)).
Hope this gets you sorted!
内容的提问来源于stack exchange,提问作者Damaris

