text.ts 930 B

1234567891011121314151617181920212223242526272829303132
  1. import { TextMatch } from 'app/types/explore';
  2. /**
  3. * Adapt findMatchesInText for react-highlight-words findChunks handler.
  4. * See https://github.com/bvaughn/react-highlight-words#props
  5. */
  6. export function findHighlightChunksInText({ searchWords, textToHighlight }) {
  7. return findMatchesInText(textToHighlight, searchWords.join(' '));
  8. }
  9. /**
  10. * Returns a list of substring regexp matches.
  11. */
  12. export function findMatchesInText(haystack: string, needle: string): TextMatch[] {
  13. // Empty search can send re.exec() into infinite loop, exit early
  14. if (!haystack || !needle) {
  15. return [];
  16. }
  17. const regexp = new RegExp(`(?:${needle})`, 'g');
  18. const matches = [];
  19. let match = regexp.exec(haystack);
  20. while (match) {
  21. matches.push({
  22. text: match[0],
  23. start: match.index,
  24. length: match[0].length,
  25. end: match.index + match[0].length,
  26. });
  27. match = regexp.exec(haystack);
  28. }
  29. return matches;
  30. }