Next.js谷歌克隆项目中,如何在JSX内对搜索结果摘要中的查询词实现条件加粗?
Great question! To dynamically bold the search term within your search result snippets, you'll need to process the snippet text to wrap matching occurrences of the term in a styled element. Here's how to implement this in your Next.js project:
Step-by-Step Implementation
Retrieve the search term from the router
Use Next.js'suseRouterhook to access the search term from the URL query parameters.Escape regex special characters
If the search term includes characters like.,*, or?, they'll break our regex pattern unless we escape them first.Split and highlight the snippet
Split the snippet text using a case-insensitive regex that matches the search term, then wrap matching parts in a bold span.
Modified SearchResults.js Code
import { useRouter } from 'next/router'; import PaginationButtons from './PaginationButtons'; // Helper function to escape special regex characters function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function SearchResults({ results }) { const router = useRouter(); const searchTerm = router.query.term || ''; // Function to highlight the search term in the snippet const highlightTerm = (snippet) => { // Return raw snippet if there's no search term if (!searchTerm.trim()) return <>{snippet}</>; const escapedTerm = escapeRegExp(searchTerm); // Split snippet into parts, including matches (case-insensitive) const regex = new RegExp(`(${escapedTerm})`, 'gi'); const snippetParts = snippet.split(regex).filter(part => part); // Filter out empty strings return ( <> {snippetParts.map((part, index) => { // Check if the part matches the search term (case-insensitive) if (part.toLowerCase() === searchTerm.toLowerCase()) { return ( <span key={index} className="font-bold text-blue-800"> {part} </span> ); } return part; })} </> ); }; return ( <div> {results.items?.map((result) => ( <div key={result.link} className="mb-4"> <p className="line-clamp-2">{highlightTerm(result.snippet)}</p> </div> ))} <PaginationButtons /> </div> ); } export default SearchResults;
Key Details:
- Case Insensitivity: The regex uses the
iflag to match the term regardless of uppercase/lowercase, just like Google's native results. - Special Character Handling: The
escapeRegExpfunction ensures terms with special characters (likereact.js) are matched correctly instead of being interpreted as regex operators. - Styling: The
font-bold text-blue-800class uses Tailwind CSS to make the term bold and blue—adjust this className to match your project's design system. - Edge Cases: If there's no search term, the function returns the raw snippet to avoid rendering empty or broken content.
内容的提问来源于stack exchange,提问作者Farzzy - MSFT

