Spaces:
Running
Running
File size: 1,825 Bytes
79278ec |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import { escapeRegExp } from "./escapeRegExp";
export function filterMatches(
matches: { match: string; index: number; element: string }[]
): { match: string; index: number; element: string }[] {
const filtered: { match: string; index: number; element: string }[] = [];
for (const current of matches) {
const isContained = filtered.some(
(existing) => current.index >= existing.index && current.index < existing.index + existing.match.length
);
if (!isContained) {
filtered.push(current);
}
}
return filtered;
}
export function getAllMatches(sortedAbbreviations: string[], input: string) {
const allMatches: { match: string; index: number; element: string }[] = [];
sortedAbbreviations.forEach((element) => {
const escapedElement = escapeRegExp(element);
const regex = new RegExp(`(?<=\\s|^|["(])(${escapedElement})(?=\\s|$|[,.!?:;")])`, "g");
let match: RegExpExecArray | null;
while ((match = regex.exec(input)) !== null) {
allMatches.push({ match: match[0], index: match.index, element });
}
});
return allMatches;
}
export function highlightMatches(input: string, matches: { match: string; index: number; element: string }[]): string {
const filteredMatches = filterMatches(matches);
filteredMatches.sort((a, b) => a.index - b.index);
let highlightedString = input;
let offset = 0;
for (const match of filteredMatches) {
const startIndex = match.index + offset;
const endIndex = startIndex + match.match.length;
highlightedString =
highlightedString.slice(0, startIndex) +
`<a href="#" class="abbreviation">${match.element}</a>` +
highlightedString.slice(endIndex);
offset += `<a href="#" class="abbreviation">${match.element}</a>`.length - match.match.length;
}
return highlightedString;
}
|