highlight.tsx 546 B

1234567891011121314151617181920212223
  1. import { ReactNode } from "react";
  2. export function highlightText(text: string, keyword: string): ReactNode {
  3. if (!keyword.trim()) {
  4. return text;
  5. }
  6. const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  7. const regex = new RegExp(`(${escaped})`, "gi");
  8. const parts = text.split(regex);
  9. return parts.map((part, index) =>
  10. regex.test(part) ? (
  11. <mark
  12. key={`${part}-${index}`}
  13. className="bg-yellow-300 text-gray-900 px-1 rounded"
  14. >
  15. {part}
  16. </mark>
  17. ) : (
  18. part
  19. )
  20. );
  21. }