parseHtmlMarks.tsx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. type Options = {
  2. htmlString: string;
  3. key: string;
  4. markTags: {
  5. highlightPostTag: string;
  6. highlightPreTag: string;
  7. };
  8. };
  9. /**
  10. * Parses the "marked" html strings into a {key, value, indices} (similar to
  11. * Fuse.js) object, where the indices are a set of zero indexed [start, end]
  12. * indices for what should be highlighted.
  13. *
  14. * @param key The key of the field, this mimics the Fuse match object
  15. * @param htmlString The html string to parse
  16. * @param markTags.highlightPreTag The left tag
  17. * @param markTags.highlightPostTag The right tag
  18. */
  19. export default function parseHtmlMarks({key, htmlString, markTags}: Options) {
  20. const {highlightPreTag, highlightPostTag} = markTags;
  21. const indices: [number, number][] = [];
  22. let value = htmlString;
  23. // eslint-disable-next-line no-constant-condition
  24. while (true) {
  25. const openIndex = value.indexOf(highlightPreTag);
  26. const openIndexEnd = openIndex + highlightPreTag.length;
  27. if (openIndex === -1 || value.indexOf(highlightPostTag) === -1) {
  28. break;
  29. }
  30. value = value.slice(0, openIndex) + value.slice(openIndexEnd);
  31. const closeIndex = value.indexOf(highlightPostTag);
  32. const closeIndexEnd = closeIndex + highlightPostTag.length;
  33. value = value.slice(0, closeIndex) + value.slice(closeIndexEnd);
  34. indices.push([openIndex, closeIndex - 1]);
  35. }
  36. return {key, value, indices};
  37. }