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

Next.js谷歌克隆项目中,如何在JSX内对搜索结果摘要中的查询词实现条件加粗?

Solution: Bold Search Term in Google API Results

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

  1. Retrieve the search term from the router
    Use Next.js's useRouter hook to access the search term from the URL query parameters.

  2. Escape regex special characters
    If the search term includes characters like ., *, or ?, they'll break our regex pattern unless we escape them first.

  3. 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 i flag to match the term regardless of uppercase/lowercase, just like Google's native results.
  • Special Character Handling: The escapeRegExp function ensures terms with special characters (like react.js) are matched correctly instead of being interpreted as regex operators.
  • Styling: The font-bold text-blue-800 class 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:57:29